3

我遇到的问题是我能够创建一个文本文件,一次写入文本。我希望能够在必要时添加更多行而不创建新文件。我的下一个问题是我似乎无法获得我正在寻找的输出。例如。文本文件包含

start1
fname|lname|ssn
end1

我的目标是只在 start1 和 end1 中获取数据,并返回 fname lname 和 ssn 而不使用分隔符 |。这是我的代码

int main()
{
    fstream filestr;
    string line;

    filestr.open ("file.txt", fstream::in | fstream::out | fstream::app);
    if(!filestr.is_open())
    {
        cout << "Input file connection failed.\n";
        exit(1); 
    }
    else{
        filestr<<"Start2\n";
        filestr<< "middle|middle"<<endl;
        filestr<<"end2"<<endl;
        if(filestr.good()){
            while(getline(filestr, line) && line !="end1"){
                if(line !="Start1"){
                    //below this point the output goes screwy
                    while(getline(filestr, line,'|')){
                        cout<<"\n"<<line;
                    }
                }
            }
        }
        filestr.close();
    }
4

2 回答 2

2

Nearly:

When you open a file for appending the read position is at the end. So before you start reading you need to seek back to the beginning (or close and re-open).

        filestr.seekg(0);

The second probelem is that you nested while loop does not check for end:

                while(getline(filestr, line,'|')){
                    cout<<"\n"<<line;

This breaks up the line. But it does not stop at the end of the line. it keeps going until it reaches the end of the file.

What you should do is take the current line and treat it as its own stream:

            if(line !="Start1")
            {   
                std::stringstream   linestream(line);
              // ^^^^^^^^^^^^^^^^^^  Add this line

                while(getline(linestream, line,'|'))
                {         //  ^^^^^^^^^^ use it as the stream
                    cout<<"\n"<<line;
                }   
            }

PS: In the file.txt

start1
^^^^^ Note not Start1
于 2012-05-09T23:52:30.233 回答
1
while(getline(filestr, line))
{
      if(line !="Start1" && line != "end1")
      {
          // Get the tokens from the string.           
      }
}
于 2012-05-09T23:54:33.170 回答