[英]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.