[英]Reading from file in c++ ifstream
I am working on a program that reads from a file and pushes back the contents of that file into a vector. 我正在研究一个从文件读取并将该文件的内容推回向量中的程序。 It will read until the file reaches a space and push that string into a vector, then continue after the space.
它将读取直到文件到达空格并将该字符串推入向量,然后在空格之后继续。 I have written this code.
我已经写了这段代码。
ifstream inFile;
inFile.open("message1.txt");
if (inFile.fail()) {
cerr << "Could not find file" << endl;
}
while (inFile >> S) {
code1.push_back(S);
}
I am just confused about the while (inFile >> S) actually does. 我只是对实际上(inFile >> S)的时间感到困惑。 I understand that it reads from the inFile until it reaches the end of file.
我了解它会从inFile读取直到到达文件末尾。 But what does the inFile >> S condition actually do?
但是inFile >> S条件实际上是做什么的? Thanks for your time.
谢谢你的时间。
The expression inFile >> S
reads a value into S
and will return inFile
. 表达式
inFile >> S
将一个值读入S
并将返回inFile
。
This allows you to chain variables together like infile >> a >> b >> c;
这使您可以将变量链接在一起,例如
infile >> a >> b >> c;
Since this inFile
is being used in a bool context , it will be converted to bool
. 由于此
inFile
在bool上下文中使用 ,因此它将转换为bool
。 And iostream
objects are defined to convert to a bool that's true
if and only if the object has no current error state. 而
iostream
对象定义转换为布尔这是true
当且仅当对象没有当前的错误状态。
What the inFile >> S
does is take in the file stream, which is the data in you file, and uses a space delimiter (breaks it up by whitespace) and puts the contents in the variable S. inFile >> S
作用是进入文件流,即文件中的数据,并使用空格定界符(用空格将其分隔)并将内容放入变量S中。
For example: 例如:
If we had a file that had the follow contents 如果我们的文件包含以下内容
the dog went running
and we used inFile >> S
with our file: 我们在文件中使用了
inFile >> S
:
ifstream inFile("doginfo.txt")
string words;
while(inFile >> words) {
cout << words << endl;
}
we will get the following output: 我们将获得以下输出:
the
dog
went
running
The inFile >> S
will continue to return true until there are no more items separated by whitespace. inFile >> S
将继续返回true,直到不再有由空格分隔的项目为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.