【问题标题】:Reading files into program将文件读入程序
【发布时间】:2014-12-06 19:17:40
【问题描述】:

我正在尝试编写一个程序: - 读取一个文本文件,然后将其放入一个字符串中 - 通过减去 4 来更改字符串中的每个字母 - 输出改变的行

我了解如何输入/输出文件。我没有比这更多的代码而且我很困惑,因为这对我来说是一个非常新的概念。我已经研究过,找不到直接的答案。如何将原始文件的每一行输入到一个字符串中然后进行修改?

谢谢!

// Lab 10
// programmed by Elijah

#include <iostream>
#include <string>
#include <fstream>
using namespace std;


int main()
{
    fstream dataFile;
//Set the file "coded" as the line input
    dataFile.open("coded.txt", ios::in);

//Create the file "plain2" as program output
    dataFile.open("plain2.txt", ios::out);

}

【问题讨论】:

    标签: c++ input output file-handling


    【解决方案1】:
    #include <iostream>
    #include <string>
    #include <fstream>
    using namespace std;
    int main()
    {
        ifstream inFile ("coded.txt"); //explicitly input using ifstream rather than fstream
        ofstream outFile ("plain2.txt"); //explicitly output using ofstream rather than fstream
        string str = "";
        char ch;
        while (inFile.get(ch))
        {
            if (ch!='\n' && ch!=' ')
            {
                //do your manipulation stuff //manipulate the string one character at a time as the characters are added     
            }str.push_back(ch); //treat the string as an array or vector and use push_back(ch) to append ch to str
        }
    }
    

    这更明确地打开输入和输出文件流,然后创建一个空字符串和统一字符。只要inFile.get(ch) 不在文件末尾,它就会返回true,并将下一个字符分配给ch。然后在循环内你可以用ch 做任何你需要做的事情。我只是将它附加到字符串中,但听起来您在附加之前需要做一些事情。

    在您的情况下,get(ch) 将比 getline() 或 >> 方法更好,因为 get(ch) 还将添加空格和制表符以及其他特殊字符,它们是 getline() 和>> 将忽略。

    如果 string-4 是指在操作行中少 4 个字符,则可以使用:

    ch = ch-4;
    

    请注意,如果 ch 最初是“a”、“b”、“c”或“d”,这可能会产生与您预期不同的结果。如果您想要环绕使用 ascii 操作和模运算符 (%)。

    【讨论】:

    • 谢谢,这很好用!一个问题:有没有办法维护原始输入文件中包含的换行符?
    • 如果你的意思是换行符,我认为这些将像任何其他字符一样存储到 ch 中。如果没有,请澄清
    • @Elijah 您可能会意外地通过减去 4 来修改 ch,如果它是换行符或空格,您将不会这样做。查看修改后的答案。
    【解决方案2】:

    您正在覆盖您的数据文件,因此您要么必须创建第二个fstream,要么先处理字符串,然后使用相同的fstream 进行输出。
    字符串读取:
    http://www.cplusplus.com/reference/string/string/getline/
    字符串修改:
    http://www.cplusplus.com/reference/string/string/replace/ “String - 4”是什么意思?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      相关资源
      最近更新 更多