c++ - 来自示例的 getline(stream, string) 被编辑器 (VS2019) 拒绝

标签 c++ visual-c++

例子取自: [ http://www-h.eng.cam.ac.uk/help/tpl/languages/C++/1AComputing/Mich/index.php?reply=extraReadingfromfiles#extraReadingfromfilesanchor][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 << "\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/

相关文章:

c++ - vs 2008 623 编译器错误

c++ - 使用已知值,如何找到二维数组的索引?

c++ - C++17 中的歧义错误(模板模板参数和默认参数问题)

c++ - 捕捉 c++ "Access Violation Writing Exception"?

c++ - 关于匿名命名空间和内部链接的标准是什么?

c++ - if 条件下两个字符串比较的优化代码

c++ - 内存是如何布局的,地址在哪个方向变大?使用 union

visual-c++ - 是否禁止重新分发 C++ 2008 Redistributable Package?

c++ - 操作 c=a+++b 是什么意思?

c++ - <ctime> 的替代品