[英]File first line is not read in c++
in.open(filename.c_str(), ifstream::in);
string name, email, group;
while (in >> name >> email >> group) {
in >> name >> email >> group;
cout << name << email << group);
...
}
in.close();
考慮這個代碼,其中in
是ifstream
類型, filename
是我們從中讀取數據的文件的名稱。 輸入文件的格式非常好 - 許多行每行3個字符串。 這件作品應該只是打印文件中的所有數據,但id的作用是打印除第一行以外的所有行。 為什么跳過第一行?
in >> name >> email >> group;
來自循環體。 條件之一就足夠了。
你讀的太多了。
while (in >> name >> email >> group)
已經讀取數據一次,下一行再次讀取數據,覆蓋數據。 擺脫重復,你的cout應該工作得很好。
in.open(filename.c_str(), ifstream::in);
string name, email, group;
while (in >> name >> email >> group) { //Reads the data into the variables
cout << name << email << group; //Outputs the variables.
...
}
in.close();
考慮這一行:
while (in >> name >> email >> group) {
每次程序到達此行時,它都會執行括號內的代碼。 在這種情況下,即使在實際進入循環體之前,也會讀取“in”並填充名稱,電子郵件,組。
因此,當執行循環體時,已經讀取了第一行。
如果你的字符串沒有被輸入文件中的新行操作符分隔,請使用代碼來讀取它。
ifstream in;
in.open("urfile.txt",ios::beg);
string name, email, group;
while (in.good()) {
in >> name >> email >> group;
cout << name << email << group;
}
in.close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.