第一次迭代成功,但后来无法输入名称。我也听说过不使用gets,所以我也尝试了fgets,但也没有用。请帮忙!!
我正在使用C ++语言编写代码块
struct stu
{
char n[25];
int r;
}s[3];
void getinfo()
{
for(int i=0;i<3;i++)
{
cout<<"name: ";
gets(s[i].n);
cout<<"R.no: ";
cin>>s[i].r;
}
}
int main()
{
getinfo();
for(int l=0;l<3;l++)
{
cout<<s[l].n;
cout<<s[l].r;
}
}
output, getting first iteration correctly but next time unable to input name
答案 0 :(得分:0)
注意:
cin.getline()
–用于从标准输入设备读取未格式化的字符串(字符集)。
提取运算符>>
不会删除行尾字符,因此,如果将其与getline()
混合使用,则需要调用
cin.ignore(number,'\n');
摆脱'\n'
#include <iostream>
#include <limits>
struct stu
{
char n[25];
int r;
}s[3];
void getinfo()
{
for(int i=0; i<3; i++)
{
std::cout << "name: ";
std::cin.getline(s[i].n,25);
std::cout << "R.no: ";
std::cin >> s[i].r;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n');
}
}
int main()
{
getinfo();
std::cout << std::endl;
for(int l=0; l<3; l++)
{
std::cout << s[l].n << " ";
std::cout << s[l].r << std::endl;
}
return 0;
}
输出:
name: Henry the VIII
R.no: 1
name: Ronald Regan
R.no: 2
name: Adam K.
R.no: 3
Henry the VIII 1
Ronald Regan 2
Adam K. 3