从文件中读取 C++ ifstream

Reading from file in c++ ifstream

我正在开发一个从文件中读取并将该文件的内容推回到向量中的程序。它会一直读取直到文件到达 space 并将该字符串推入向量,然后在 space 之后继续。我已经写了这段代码。

  ifstream inFile;
            inFile.open("message1.txt");
            if (inFile.fail()) {
                    cerr << "Could not find file" << endl;
            }
            while (inFile >> S) {
                    code1.push_back(S);
            }

我只是对 while (inFile >> S) 的实际作用感到困惑。我知道它从 inFile 读取直到到达文件末尾。但是 inFile >> S 条件实际上做了什么?谢谢你的时间。

表达式 inFile >> S 将值读入 S 并且 将 return inFile.

这允许您将变量链接在一起,如 infile >> a >> b >> c;

由于此 inFile 布尔上下文 中使用,因此它将被转换为 bool。并且 iostream 对象被定义为转换为布尔值 true 当且仅当对象没有当前错误状态时。

inFile >> S 所做的是获取文件流,即文件中的数据,并使用 space 分隔符(用白色 space 分隔)和将内容放入变量 S.

例如:

如果我们有一个包含以下内容的文件

the dog went running

并且我们在文件中使用了 inFile >> S

ifstream inFile("doginfo.txt")
string words;
while(inFile >> words) {
   cout << words << endl;
}

我们将得到以下输出:

the
dog
went
running

inFile >> S 将继续 return true,直到没有更多的项目被白色分隔 space。