从文件中读取,仅读取文本,直到它到达空白空间

发布于 2024-12-10 05:31:08 字数 421 浏览 1 评论 0原文

我设法成功读取文件中的文本,但它只会读取直到遇到空白区域,例如文本:“嗨,这是一个测试”,cout 为:“嗨,”。

删除“,”没有什么区别。

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

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

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

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

I managed to successfully read the text in a file but it only reads until it hits an empty space, for example the text: "Hi, this is a test", cout's as: "Hi,".

Removing the "," made no difference.

I think I need to add something similar to "inFil.ignore(1000,'\n');" to the following bit of code:

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

I would prefer not to change to getline(inFil, variabel); because that would force me to redo a program that is essentially working.

Thank you for any help, this seems like a very small and easily fixed problem but I cant seem to find a solution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

饭团 2024-12-17 05:31:08
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::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";
}

This will help you read the file. I don't know what you are trying to achieve since your code is not complete but the above code is commonly used to read files in c++.

绿光 2024-12-17 05:31:08

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

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

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

You've been using formatted extraction to extract a single string, once: this means a single word.

If you want a string containing the entire file contents:

std::fstream fs("/path/to/file");
std::string all_of_the_file(
   (std::istreambuf_iterator<char>(filestream)),
   std::istreambuf_iterator<char>()
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文