【问题标题】:Read text file display to console then append text file读取文本文件显示到控制台然后附加文本文件
【发布时间】:2014-08-07 09:32:23
【问题描述】:

我有一个名称的文本文件。我想将文本文件读入流中,将其显示到控制台。完成后,它将提示用户输入他们的姓名。然后它应该将其添加到文件中。

我可以让它分别做这两件事,但不能一起做。 这是我的代码。

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;
using namespace System;

int main(array<System::String ^> ^args)
{
 fstream myfile;
 string line;
 string name;
    myfile.open("Names.txt",ios::out | ios::in | ios_base::app);
    if (myfile.is_open())
    { 
      while( getline(myfile, line) )
      {
          cout << line << endl;
      }
     cout << "Enter your name!\n";
     getline (cin, name);
     myfile << name;
     myfile.close();
 }
 else
 {
     cout << "file was not opened\n";
 }

    return 0;
}

如果我将 while 循环留在其中,它会将所有名称写入控制台,但不会将用户输入的名称附加到列表中。如果我取出 while 循环,我可以为文件添加一个名称,但当然我不会得到该文件中已经存在的名称列表。

我最好的猜测是,我认为这可能与以下事实有关信息流中没有剩余空间了吗?

【问题讨论】:

  • 那不是 C++:array&lt;System::String ^&gt; ^args)?!?
  • 我使用的是Visual Studio,我选择了项目类型CLR Console App。它是为我提供的。
  • 看起来你需要更多标签。
  • 正如我的问题所解释的那样,对 C++ 来说非常陌生。这会影响我尝试使用此文件 IO 做什么吗?
  • 我不认为会,但我不能肯定地说。

标签: c++ file-io iostream


【解决方案1】:

你的猜测是正确的。

getline() 的最后一次调用(失败的那个)在您的流上设置了错误标志,这将导致任何进一步的 IO 尝试失败,这就是您的文件中实际上没有写入任何内容的原因。

您可以在阅读循环后重置errors flags with clear()

myfile.clear();

注意:

您还应该测试上一次getline() 调用的返回值。

【讨论】:

  • 非常感谢!当修复很简单时,这很好。
【解决方案2】:

刚刚碰到这个问题,即使这里有公认的答案,我认为可以使用完整的代码来展示如何使用规范的 C++ 文件读取循环:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;
using namespace System;

int main(array<System::String ^> ^args)
{
 fstream myfile;
 string line;
 string name;
    myfile.open("Names.txt",ios::out | ios::in | ios_base::app);
    if (myfile.is_open())
    { 
      while( getline(myfile, line) )
          cout << line << endl;
      if (file_list.eof())
          file_list.clear();  //otherwise we can't do any further I/O
      else if (file_list.bad()) {
          std::cout << "Error occured while reading file";
          return 1;
     }
     cout << "Enter your name!\n";
     getline (cin, name);
     myfile << name;
     myfile.close();
 }
 else
 {
     cout << "file was not opened\n";
 }

    return 0;
}

【讨论】:

    猜你喜欢
    • 2013-12-26
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    相关资源
    最近更新 更多