作为一个编程新手,C++是我的第一门语言。如果可能的话,请包含一些解释。
我必须从包含混合变量的文件中读取行。我目前面临2个问题:
循环输入语句,以便我可以读取所有行。我只能使用以下代码来执行循环:
while(inputFile.peek() != EOF)
我确实理解这应该检查下一个字符,如果它是EndOfFile,它会跳出循环,但我无法让它正常工作。
读取由布尔值前导的字符串(跳过空格)。为了跳过空格,我应该使用:
while(inputFile.peek() == ' ') inputFile.get();
文件内容如下:
Car CN 819481 maintenance false NONE
Car SLSF 46871 business true Memphis
Car AOK 156 tender true McAlester
下面是我的代码。我省略了main()
函数,因为它唯一的作用就是调用input()
函数。
#include <iostream> //used in main()
#include <iomanip>
#include <string>
#include <fstream> //to work with file
#include <cstdlib> //for exit() function
using namespace std;
void input(){
ifstream inputFile;
string type, rMark, kind, destination;
int cNumber;
bool loaded;
inputFile.open("C:\\My Folder\\myFile.txt"); //open file
if (!inputFile){
cerr << "File failed to open.\n";
exit(1);
}
//read file contents
while(inputFile.peek() != EOF){
//initially I had >>destination in the statement below as well
//but that gave me the same results.
inputFile >> type >> rMark >> cNumber >> kind >> loaded;
//skip whitespace
while(inputFile.peek() == ' '){
inputFile.get();
}
//get final string
getline(inputFile, destination);
cout << type << " " << rMark << " " << cNumber << " " << kind << " ";
cout << boolalpha << loaded << " " << destination << endl;
}
inputFile.close(); //close file
} //end input()
运行程序后,我得到了:
Car CN 819481 maintenance false
所以第一行代码读取到布尔值为止(最后的字符串被省略),但循环不起作用(或者它在读取不该读的东西吗?)。我已经尝试过移动.peek()和.gets(),但没有任何组合可行。
提前感谢!