【问题标题】:C++ cant read file and append gives strange results [closed]C ++无法读取文件并追加给出奇怪的结果[关闭]
【发布时间】:2014-06-07 19:41:12
【问题描述】:

我有一个菜单,可以根据用户的选择启动一些方法。然而,其中两种方法不能正常工作,我不知道为什么。 这是他们菜单的一部分:

case 2:
{
    string fileName;
    cout << "Which file to read?:";
    cin>>fileName;
    this->ReadFromFile(fileName);
    break;
}
case 3:
{
    string fileName;
    cout << "Enter name for the file:";
    cin>>fileName;
    this->WriteToFile(fileName);
    break;
}

方法如下:

void ReadFromFile(string file)
    {
        string line;
        ifstream rfile ("FileSystem/" + file);//open file for reading
        if (rfile.is_open())
        {
            while(getline(rfile, line))
            {
                cout << line << endl;
            }
        }
        else
        {
            cout << "An error occurred when tried to read from this file." << endl;
        }
        rfile.close();
        _getch();
    }

    void WriteToFile(string fileName)
    {
        ofstream myFile;
        ifstream exists (fileName);//open read stream to check if file exists
        if(exists)//returns true if file can be opened and false if it cant
        {
            exists.close();//close the stream
            myFile.open(fileName, ios_base::app);// open file for reading(ostream)
        }
        else
        {
            exists.close();
            CreateFile(fileName);//file doenst exists, so we create one and list it in the file tree
            myFile.open("FileSystem/" + fileName, ios_base::app);// open file for reading(ostream)
        }
        if(myFile.is_open())
        {
            string input;
            cout << "start writing and press enter to finish. It will be done better later." << endl;
            cin>>input;
            myFile << input;

        }
        else
        {
            cout<<"An error occurred when tried to open this file."<<endl;
        }
        myFile.close();
        _getch();
    }

现在是有趣的部分。当我尝试向文件写入内容时,使用以下命令打开它并不重要:'ios_base::app' 或 'ios:app' 它只是重写它。但它甚至不能正确地做到这一点。如果我有一行空格,例如“嗨,这是我。”例如,它只写第一个单词,这里是'Hi'。 因此,如果我决定读取该文件,首先发生的事情是它说该文件无法打开,甚至在它要求我输入名称之前也是如此。这发生在前 3 次尝试中,然后阅读神奇地起作用。 在过去的两个小时里,我一直在努力解决这个问题,但我仍然无法理解发生了什么。谁能向我解释一下,并告诉我我的错误?

【问题讨论】:

  • 窄,窄,窄!首先使用调试器!

标签: c++ stream fstream ifstream ofstream


【解决方案1】:
string input;
cout << "start writing and press enter to finish. It will be done better later." << endl;
cin>>input;
myFile << input;

在上面的行中,cin&gt;&gt;input 将在空格处停止读取。您应该改用std::getline。另见this answer

【讨论】:

  • 当我使用 std::getline(std::cin,input) 它在我按下第一个键后停止。它不写任何东西,而且它会删除文件中的所有内容。
  • 您之前的阅读操作 (cin&gt;&gt;fileName;) 不会“吃掉”换行符。因此 getline 只读取您在文件名之后输入的换行符。见How do I flush the cin buffer?
  • 谢谢,解决了。除此之外,我发现我试图查找是否可以由于某种原因打开文件的方式总是返回 false。反正我也修好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 2013-08-20
  • 2019-12-17
相关资源
最近更新 更多