我正在编写一个程序,它必须将文件中的数据导入各种容器。我有它正确导入所有内容,但它继续阅读之后应该是eof。我有一种感觉,我没有正确告诉循环何时结束,但代码在下面供所有人查看。
bool InitLoad(vector<string>&num, vector<string>&name, vector<double>&price, vector<char>&tax)
{
ifstream invFile;
int intTemp;
string strTemp;
double dubTemp;
char chTemp;
string fileLoc = "C:/Users/owner/Documents/Visual Studio 2010/Projects/CISS 350/Week 1 Grocery Register/Week 1 Grocery Register/Invent.dat";
//Open Invent.dat file. Location below is the location used on creators computer. Other may need to modify file location
invFile.open(fileLoc.c_str(), ios::in);
//If Invent.dat file fails to open display error message and return false
if(invFile.fail())
{
cout << "Could not open inventory file" << endl;
return false;
}
if(invFile)
{
//Read first line of the file
getline(invFile, strTemp, ' ');
while(invFile) //while invFile contains data display import the list
{
cout << strTemp << " ";
num.push_back(strTemp);
getline(invFile, strTemp, ' ');
cout << strTemp << " ";
name.push_back(strTemp);
getline(invFile, strTemp, ' ');
dubTemp = atof(strTemp.c_str());
cout << dubTemp << " ";
price.push_back(dubTemp);
invFile.get(chTemp);
cout << chTemp;
tax.push_back(chTemp);
getline(invFile, strTemp, ' ');
}
}
invFile.close();
cout << endl;
//Verify Proper input...REMOVE WHEN COMPLETE
cout << "Verifying input data correct..." << endl;
int vecSize = num.size();
cout << vecSize << endl;
for(int i = 0; i < vecSize; i++)
{
cout << num[i] << " " << name[i] << " " << price[i] << " " << tax[i] << endl;
}
}
答案 0 :(得分:4)
您的支票不会检查eof标志 http://www.cplusplus.com/reference/ios/ios/operator_bool/
使用invFile.eof()
代替
在读完EOF
之后,还会设置eof标志 PS:OMG !!不要使用atof
,只需执行invFile << dubTemp
答案 1 :(得分:0)
由于数据是空格分隔的,因此您可以在每个字符串上使用格式化输入而不是getline()。 有点像这样。
string lineTemp;
while(getline(invFile, lineTemp)) //while invFile contains data display import the list
{
string strTemp1, strTemp1, dubTemp, chTemp;
istringstream lstr(lineTemp);
if(lstr >> strTemp1 >> strTemp2 >> dubTemp >> chTemp) {
num.push_back(strTemp1);
name.push_back(strTemp2);
price.push_back(dubTemp);
tax.push_back(chTemp);
cout << strTemp1 << " "
<< strTemp2 << " "
<< dubTemp << " "
<< chTemp << endl;
}
else {
// Something is wrong with the line format.
}
}
这将以格式化方式和正确类型读取数据。另外,您不必担心行中的空行或额外字符。