【问题标题】:fstream to display all text in txtfstream 显示 txt 中的所有文本
【发布时间】:2014-11-01 06:57:45
【问题描述】:

我想将填充中的所有文本显示到输出, 我使用下面的代码,我起床的代码和结果帖子只是有点出来

#include <fstream>
#include <iostream>

using namespace std;

int main()
{
  char str[10];

  //Creates an instance of ofstream, and opens example.txt
  ofstream a_file ( "example.txt" );
  // Outputs to example.txt through a_file
  a_file<<"This text will now be inside of example.txt";
  // Close the file stream explicitly
  a_file.close();
  //Opens for reading the file
  ifstream b_file ( "example.txt" );
  //Reads one string from the file
  b_file>> str;
  //Should output 'this'
  cout<< str <<"\n";
  cin.get();    // wait for a keypress
  // b_file is closed implicitly here
}

上面的代码只是简单的显示“This”这几个字并没有全部输出到output.yang我想要的是文件中的所有文本都出现在控制台中..

【问题讨论】:

    标签: c++ iostream


    【解决方案1】:

    char* 的重载 operator&gt;&gt; 只会读取到第一个空格字符(这也是非常风险,如果它尝试读取比你结束的 buf 长度更长的单词有未定义的行为)。

    只要您的编译器支持右值流重载,以下内容应该以最简单的方式执行您想要的操作(如果不是,您必须创建一个本地 ostream 变量,然后使用流运算符):

    #include <fstream>
    #include <iostream>
    
    int main()
    {
      std::ofstream("example.txt") << "This text will now be inside of example.txt";
      std::cout << std::ifstream("example.txt").rdbuf() << '\n';
    }
    

    【讨论】:

      【解决方案2】:

      试试这样的

       #include <fstream>
       #include <iostream>
      
       using namespace std;
      
       int main(){
        string line;
        ofstream a_file ( "example.txt" );
        ifstream myfile ("filename.txt");
        if (myfile.is_open()) {
         while ( getline (myfile,line) ) {
            a_file << line << '\n';
         }
        myfile.close();
        a_file.close();
        } else 
            cout << "Unable to open file"; 
       }
      

      希望有帮助

      【讨论】:

        【解决方案3】:

        这不是从文件中读取的最佳方式。您可能需要使用 getline 并逐行阅读。请注意,您使用的是固定大小的缓冲区,可能会导致溢出。不要那样做。

        这是一个与您希望达到的目标相似的示例,而不是最好的做事方式。

        #include <fstream>
        #include <iostream>
        
        using namespace std;
        
        int main() {
          string str;
          ofstream a_file("example.txt");
          a_file << "This text will now be inside of example.txt";
          a_file.close();
          ifstream b_file("example.txt");
          getline(b_file, str);
          b_file.close();
          cout << str << endl;
          return 0;
        }
        

        【讨论】:

          【解决方案4】:

          这是一个重复的问题:

          reading a line from ifstream into a string variable

          正如您从 C++ 的文本输入/输出中知道的那样,cin 最多只能读取换行符或空格。如果要阅读整行,请使用std::getline(b_file, str)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-07-15
            • 2020-12-12
            • 1970-01-01
            • 1970-01-01
            • 2012-08-29
            • 1970-01-01
            • 2011-11-10
            • 2021-07-24
            相关资源
            最近更新 更多