编辑器(VS2019)拒绝了示例中的getline(stream,string)

getline(stream, string) from example is rejected by editor(VS2019)

本文关键字:getline stream string VS2019 拒绝 编辑器      更新时间:2023-10-16

示例取自:[http://www-h.eng.cam.ac.uk/help/tpl/languages/C++/1计算/Mich/index.php?reply=extraReadingfromfiles#extraReading fromfiles anchort][1]

我写的代码没有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 << "nt Couldn't open the s file." << endl;
cout << "nt 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);
}

我的问题是,为什么现在评论的行被拒绝了?

fin>>消息;当您想从文件中读取单个单词时,会使用流提取运算符">>"。完整解释请访问:https://www.google.com/amp/s/www.geeksforgeeks.org/cpp-program-read-file-word-word/amp/

Whilegetline(fin,message);在这种情况下,将在消息变量中读取文件中的一整行。它将继续读取和分配文件内容,直到不出现'\n'(行除法器)字符为止。这就是为什么getline()语句被拒绝的原因。如需完整解释,请访问:http://www.cplusplus.com/forum/windows/48212/

您的程序应该一次读取一个单词。为了实现这一点,使用了鳍>>台面。基本上,流提取操作符读取内容,直到出现一个空格,因此它用于读取单个单词。

如果您仍然想使用getline(),那么在函数调用中添加第三个参数作为空格字符"。喜欢getline(fin,message,'');//并且完成基本上,getline函数的第三个参数是Deliminator,默认情况下是'\n',但如果您想定义自己的Deliminato,可以通过提供第三个变量来实现。它将读取文件的内容,直到在读取时没有出现Deliminator为止。

要使用std::getline(),请在标头中包含<string>。https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/2whx1zkx(v=vs.100)

istream也有一个getline。此处提供更多详细信息https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-6.0/aa277361(v=vs.60)