将文件读入程序

Reading files into program

本文关键字:程序 文件      更新时间:2023-10-16

我正在尝试编写一个程序:-读取文本文件,然后将其放入字符串中-通过减去 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);
}
#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 操作和模运算符 (%)。

您正在覆盖 dataFile,因此您必须创建第二个fstream或先处理字符串,然后使用相同的fstream进行输出。
字符串读取:

http://www.cplusplus.com/reference/string/string/getline/字符串修改:
http://www.cplusplus.com/reference/string/string/replace/"字符串 - 4"是什么意思?