![](/img/trans.png)
[英]New to C++ and wondering what getline() and cin are doing in my code
[英]std::getline is not doing what I expect it to do See my code below
我正在使用 RHEL5.4、QT4.8 只有文件的第一行在 getline 中得到處理。 我在 stringstream ss 上的 qDebug 打印文件中的所有行。 我的記錄結構上的 qDebug 重復文件第一行中的數據,以獲得文件中的總行數。 我對結果向量的 qDebug 再次重復文件第一行中的數據,以獲得文件中的總行數。
首先我在頭文件中聲明一個記錄結構。
struct data_rec
{
std::string name;
std::string value;
};
std::ifstream myfile("foo.bar");
if(!myfile.is_open()){
qDebug() << "Could not open file";
}else {
qDebug() << "File opened";
std::string line;
std::stringstream ss;
std::stringstream tss;
while(std::getline(myfile,line))
{
data_rec records;
tss.str("");
ss<<line<<std::endl;
tss<<line<<std::endl; //; temp stringstream
std::getline(tss, records.name, ',');
std::getline(tss, records.value, ',');
qDebug()<<"!!!" << records.name.c_str();
qDebug()<<"!!!" << records.value.c_str();
result.push_back(records);
tss.str(std::string());
}
for(int x = 0; x < 46; x++)
{
QString tstr1 = QString::fromStdString(result[i].name);
QString tstr2 = QString::fromStdString(result[i].value);
qDebug() << tstr1 << " -> " << tstr2;
}
qDebug() << QString::fromStdString(ss.str());
qDebug() << "\n////////////////////////////////////////\n";
myfile.close();
}
您在每次循環迭代中重用tss
,但您沒有在每次迭代中清除其錯誤狀態,只清除其字符串內容。 當第一次迭代完成時,如果該行沒有以','
字符終止,則流可能已達到 EOF 並且現在處於錯誤狀態。 使用空字符串調用tss.str()
不會清除錯誤狀態,您需要為此調用tss.clear()
,否則對getline(tss)
的下一次調用將失敗。
while (std::getline(myfile, line))
{
data_rec records;
// tss.str(""); // <-- redundant here!
ss << line << std::endl;
tss << line << std::endl;
std::getline(tss, records.name, ',');
std::getline(tss, records.value, ',');
qDebug() << "!!!" << records.name.c_str();
qDebug() << "!!!" << records.value.c_str();
result.push_back(records);
tss.str(std::string());
tss.clear(); // <-- add this!
}
否則,根本不要重用stringstream
,在每次迭代時創建一個新的:
while (std::getline(myfile, line))
{
data_rec records;
std::istringstream tss(line); // <-- here!
ss << line << std::endl;
std::getline(tss, records.name, ',');
std::getline(tss, records.value, ',');
qDebug() << "!!!" << records.name.c_str();
qDebug() << "!!!" << records.value.c_str();
result.push_back(records);
}
也就是說,當while
循環結束時,您的后續for
循環假定result
包含 46 個元素,但while
循環中沒有任何內容可以保證這一點。 for
循環應該查看result.size()
:
for(size_t x = 0; x < result.size(); x++)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.