函数不会读取完整输入

Function will not read full input

本文关键字:输入 读取 函数      更新时间:2023-10-16

我调用一个函数,就像这样getseconddata (list2,n)

输入文件读取

45 P 19
11 S 56
45 S F
30 P F

并且函数代码读取

void getseconddata(employeetype list2[], int n)
{
ifstream infile2;
  string filename;
  int id, changenum;
  char stat, changealpha;
cout<<"Enter name of second data file"<<endl;
  cin>>filename;
  infile2.open(filename.c_str());
  infile2>>id;
  while (getline(infile2))
    {
infile2>>stat;
      if (stat=='S')
        {
        infile2>>changealpha;
        }
      else if (stat=='P')
        {
    infile2>>changenum;
        }
      infile2>>id;
    }
  infile2.close();
  for (int i=0; i<n; i++)
    {
  cout<<id<<stat<<changealpha<<changenum<<endl;
}
}

输出读取

45 P 19
45 P 19
45 P 19
45 P 19

我尝试重写代码并在线查找基本功能和 eof。

帮助

首先:你对getline的使用不正确,你的代码不应该编译。

while(getline(infile2)) { ... }

infile2是一个ifstream。没有getline的签名需要ifstream&.有一个签名需要ifstreamstring,像这样使用:

stringstream buffer;
while(getline(infile2, line)) {
    buffer << line;
    buffer >> id >> stat;
    // ...
    buffer.clear() // to reset for next iteration
}

第二:您接收的输出是您的for循环指示的输出。

for (int i=0; i<n; i++) {
    cout << id << stat << changealpha << changenum << endl;
}

这个for循环,如果你对getline的使用是正确的,将输出30 P F,最后一行的数据,n次。它不会输出n不同的list2索引。原因是您的变量在 while 循环的每次迭代中都会重置,并且由于您的 for 循环是在while循环之后运行的,因此它只会从最后一行输出开始。

第三:您的if-else-if条件指示输入文件以外的其他内容。

if(stat == 'S') {
    infile2 >> changealpha; // 'changealpha' is a 'char'
} else if(stat == 'P') {
    infile2 >> changenum;   // 'changenum' is an 'int'
}

上述逻辑不适合输入文件的格式:

45 P 19 // 'stat' is P suggests 'int'  - correct
11 S 56 // 'stat' is S suggests 'char' - ??? - there are 3 chars after S (' ', '5', '6')?
45 S F  // 'stat' is S suggests 'char' - correct
30 P F  // 'stat' is P suggests 'int'  - ??? - do you want the ASCII char code of 'F'?