fstream以txt格式显示所有文本

fstream to display all text in txt

本文关键字:文本 显示 格式 txt fstream      更新时间:2023-10-16

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

#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"并没有全部输出。我想要的是文件中的所有文本都显示在控制台中。。

char*的重载operator>>将只读取到第一个空白字符(这也是非常的风险,如果它试图读取比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';
}

尝试类似的东西

 #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"; 
 }

希望对有所帮助

这不是读取文件的最佳方式。您可能需要使用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;
}

这是一个重复的问题:

将ifstream中的一行读取到字符串变量中

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