函数不会读取完整输入
Function will not read full input
我调用一个函数,就像这样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&
.有一个签名需要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;
}
这个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'?
相关文章:
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 套接字读取后,我在缓冲区中看到意外输入
- 从标准输入读取文件后读取用户输入
- C++ 从标准输入读取文件名
- 从标准输入读取多个类型时出现问题
- 使用 fgets() 从键盘读取时从以前的输入读取换行符
- 从标准输入读取时zmq_poll不侦听信号
- 从超强的AndroidAudioIO输入读取缓冲区
- 如何实现将用户输入读取到提供的所有变量中的可变参数模板
- 如何使用重定向的标准输入读取文件,即cin(注意:不使用ifstream)
- 将空格分隔的输入读取到C++中的数组中
- Win32 - 从标准输入读取超时
- 从标准输入读取输入,并准备接收来自服务器的广播
- 终止将输入读取到int中的内容
- 如何从标准输入读取输入,直到按下空格或选项卡
- DirectX 11输入读取方法
- 将输入读取到动态大小的数组中