-2

我设法成功地读取了文件中的文本,但它只读取到它碰到一个空白空间,例如文本:“嗨,这是一个测试”,cout 为:“嗨”。

删除“,”没有任何区别。

inFil.ignore(1000,'\n');我想我需要在以下代码中添加类似于“ ”的内容:

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

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

感谢您的帮助,这似乎是一个非常小且易于解决的问题,但我似乎无法找到解决方案。

4

2 回答 2

4
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++ 中的文件。

于 2011-10-15T13:11:07.460 回答
2

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

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

std::fstream fs("/path/to/file");
std::string all_of_the_file(
   (std::istreambuf_iterator<char>(filestream)),
   std::istreambuf_iterator<char>()
);
于 2011-10-15T13:26:09.530 回答