【问题标题】:Function will not read full input函数不会读取完整的输入
【发布时间】:2016-03-10 01:57:46
【问题描述】:

我这样调用函数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。帮助

【问题讨论】:

    标签: c++ function if-statement while-loop ifstream


    【解决方案1】:

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

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

    infile2 是一个ifstream。没有getline 的签名采用ifstream&amp;。有一个签名需要一个ifstream 和一个string,这样使用:

    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;
    }
    

    如果您对getline 的使用正确,这个for 循环将输出30 P F,最后一行的数据n 次。它不会输出nlist2 的不同索引。原因是您的变量在 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'?
    

    【讨论】:

      猜你喜欢
      • 2016-10-27
      • 2012-04-06
      • 2016-03-27
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多