将文件读入程序

时间:2014-12-06 19:17:41

标签: c++ input output file-handling

我正在尝试编写一个程序: - 读取文本文件,然后将其放入字符串中 - 通过减去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);

}

2 个答案:

答案 0 :(得分: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()或&gt;&gt;方法,因为get(ch)还将添加空格和制表符以及作为getline()和&gt;&gt;的文件一部分的其他特殊字符。会忽略。

如果字符串为4,则表示您可以使用的操作行中的字符数少于4:

ch = ch-4;

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

答案 1 :(得分:0)

您正在覆盖您的dataFile,因此您必须先创建第二个fstream或先处理字符串,然后再使用相同的fstream进行输出。
字符串阅读:
http://www.cplusplus.com/reference/string/string/getline/
字符串修改:
http://www.cplusplus.com/reference/string/string/replace/ 你是什​​么意思&#34;字符串 - 4&#34;?

相关问题