从文件中读取,只读取文本,直到它变成空白

Reading from a file, only reads text untill it gets to empty space

本文关键字:空白 取文本 文件 读取 只读      更新时间:2023-10-16

我成功地读取了文件中的文本,但它只读取,直到它遇到一个空白的空间,例如文本:"嗨,这是一个测试",cout's as: "嗨,".

去掉","没有影响。

我想我需要添加类似于"inFil.ignore(1000,'n');"的东西到下面的代码位:

inFil>>text;
inFil.ignore(1000,'n');
cout<<"The file cointains the following: "<<text<<endl;

我不希望更改为getline(inFil, variabel);,因为这将迫使我重做一个本质上工作的程序。

谢谢你的任何帮助,这似乎是一个非常小的和容易修复的问题,但我似乎找不到一个解决方案。

std::ifstream file("file.txt");
if(!file) throw std::exception("Could not open file.txt for reading!");
std::string line;
//read until the first n is found, essentially reading line by line unti file ends
while(std::getline(file, line))
{
  //do something line by line
  std::cout << "Line : " << line << "n";
}

这将帮助您读取文件。我不知道你想要实现什么,因为你的代码不完整,但上面的代码通常用于在c++中读取文件。

您一直在使用格式化提取来提取单个字符串,一次:这意味着单个单词。

如果你想要一个包含整个文件内容的字符串:

std::fstream fs("/path/to/file");
std::string all_of_the_file(
   (std::istreambuf_iterator<char>(filestream)),
   std::istreambuf_iterator<char>()
);