我写的代码没有while循环读取文件,例子中使用了getline(stream, strgvar)
,但是小编不承认这一点
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string message;
ifstream fin; // variable to store information about a file
fin.open("s.txt"); // trying to open file for reading
// next line would try to check if file has been opened succesfully
if (not fin.good())
{
cout << "\n\t Couldn't open the s file." << endl;
cout << "\n\t It needs to be in the same folder as your program."
<<endl;
return 1; // In the main function this line quits from the
whole program.
}
// we have menaged to open the file. Now we'll read a line from the file into the string
while (message!="works!")
{
fin >> message;
cout << message << " ";
}
//getline(fin,message);
}
我的问题是为什么现在评论的行被拒绝了?
最佳答案
鳍>>消息; 当您想从文件中读取单个单词时,使用流提取运算符“>>”。 在以下位置找到完整的解释:https://www.google.com/amp/s/www.geeksforgeeks.org/cpp-program-read-file-word-word/amp/
同时 getline(鳍,消息); 在此,文件中的整行将被读取到消息变量中。它将继续读取和分配文件内容,直到不出现 '\n'(行分隔符)字符。这就是为什么您的 getline() 语句被拒绝的原因。 如需完整说明,请访问:http://www.cplusplus.com/forum/windows/48212/
您的程序应该一次读取一个单词。为此,使用了 fin>>mesage。基本上流提取运算符读取内容直到出现空格,因此它用于读取单个单词。
如果您仍想使用 getline(),则将第三个参数添加到您的函数调用中作为空格字符 ' '。 喜欢 getline(fin, 消息, ' ');//并做了 基本上 getline 函数的第三个参数是 Deliminator,默认是 '\n',但是如果你想定义你自己的 Deliminator,你可以通过提供第三个参数来实现。它将读取文件的内容,直到读取时不出现分隔符。
关于c++ - 来自示例的 getline(stream, string) 被编辑器 (VS2019) 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54637907/