简体   繁体   English

文件第一行不是用c ++读取的

[英]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();

Consider this code where in is of type ifstream and filename is the name of the file from which we read the data. 考虑这个代码,其中inifstream类型, filename是我们从中读取数据的文件的名称。 Format of input file is perfectly fine - many lines with 3 string in each. 输入文件的格式非常好 - 许多行每行3个字符串。 This piece should simply print all of the data in the file but what id does is printing all of the lines except for the first line. 这件作品应该只是打印文件中的所有数据,但id的作用是打印除第一行以外的所有行。 Why is the first line skipped? 为什么跳过第一行?

Drop in >> name >> email >> group; in >> name >> email >> group; from the body of the loop. 来自循环体。 The one in the condition is enough. 条件之一就足够了。

You're reading too much. 你读的太多了。

while (in >> name >> email >> group)

Already reads the data once, the next line reads it again, overwriting your data. 已经读取数据一次,下一行再次读取数据,覆盖数据。 Get rid of the repetition and your cout should work just fine. 摆脱重复,你的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();

Consider this line: 考虑这一行:

while (in >> name >> email >> group) {

each time the program hits this line, it executes the code inside the brackets. 每次程序到达此行时,它都会执行括号内的代码。 In this case, 'in' is read and populates name, email, group even before actually entering the body of the loop. 在这种情况下,即使在实际进入循环体之前,也会读取“in”并填充名称,电子邮件,组。

Thus, when the body of the loop is executed, the first line has already been read. 因此,当执行循环体时,已经读取了第一行。

If you strings are not seperated by new line operator in the input file use code the blow to read it. 如果你的字符串没有被输入文件中的新行操作符分隔,请使用代码来读取它。

  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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM