2015-02-18 126 views
0

我正在研究从文件读取并将该文件的内容推回到向量中的程序。它会读取,直到文件到达一个空间并将该字符串推入矢量,然后在该空间后继续。我写了这段代码。从C++ ifstream中读取文件

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

我对这段时间(inFile >> S)实际上只是感到困惑。我知道它从inFile中读取,直到文件结束。但inFile >> S条件实际上做了什么?谢谢你的时间。

回答

1

inFile >> S做什么是采取文件流,这是在你的文件中的数据,并使用空格分隔符(由空格打破它),并把内容的变量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将继续,直到没有用空格分隔多个项目返回true。

2

表达式inFile >> S将值读入S将返回​​

这允许您链变量在一起像infile >> a >> b >> c;

由于这​​在布尔上下文正在被使用,它会被转换为bool。并且iostream对象被定义为当且仅当对象没有当前错误状态时才转换为true