c++ - 为什么我的 C++ 代码在执行前没有接受所有输入?它只需要输入并打印所有 cout 内容
问题描述
这是我的代码和结果,我只是先创建一个结构,然后设置一个 for 循环以使用该元素并从用户那里获取输入并在代码部分的最后显示。请帮我
#include <iostream>
using namespace std;
struct person
{
char name[30];
int age;
int phone_no;
}p[5];
int main()
{
for (int i=0; i<5; ++i)
{
cout<<"Enter you details \n\n\n";
cout<<" Enter your name : ";
cin.get(p[i].name,30);
cout<<"\n Enter your age : ";
cin>>p[i].age;
cout<<"\n Enter your phone no : ";
cin>>p[i].phone_no;
}
for (int i=0; i<5; ++i)
{
cout<<"\n\n\n Person's name : "<<p[i].name<<"\n Age : "<<p[i].age<<"\n Phone no : "<<p[i].phone_no;
}
return 0;
}
结果
Enter you details
Enter your name : Ram
Enter your age : 12
Enter your phone no : 9898874645
Enter you details
Enter your name :
Enter your age :
Enter your phone no : Enter you details
Enter your name :
Enter your age :
Enter your phone no : Enter you details
Enter your name :
Enter your age :
Enter your phone no : Enter you details
Enter your name :
Enter your age :
Enter your phone no :
Person's name : Ram
Age : 12
Phone no : 2147483647
Person's name :
Age : 0
Phone no : 0
Person's name :
Age : 0
Phone no : 0
Person's name :
Age : 0
Phone no : 0
Person's name :
Age : 0
Phone no : 0
Process exited after 12.16 seconds with return value 0
Press any key to continue . . .
如果您对我的代码技能有任何疑问,我还想给您一些有用的建议
解决方案
问题是:
- 电话号码太大,无法适应
int
此环境。它应该存储为字符串。 >>
运算符 forcin
在流中留下换行符,因此下一个cin.get()
将读取并停在那里。您可以阅读直到换行符并删除通过cin.ignore()
. 请注意,这cin.get()
也会留下换行符,但>>
操作员会忽略这一点。
尝试这个:
#include <iostream>
#include <limits>
using namespace std;
struct person
{
char name[30];
int age;
char phone_no[30];
}p[5];
int main()
{
for (int i=0; i<5; ++i)
{
cout<<"Enter you details \n\n\n";
cout<<" Enter your name : ";
cin.get(p[i].name,30);
cout<<"\n Enter your age : ";
cin>>p[i].age;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout<<"\n Enter your phone no : ";
cin.get(p[i].phone_no,30);
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
for (int i=0; i<5; ++i)
{
cout<<"\n\n\n Person's name : "<<p[i].name<<"\n Age : "<<p[i].age<<"\n Phone no : "<<p[i].phone_no;
}
return 0;
}
推荐阅读
- phpstorm - 如何在 PhpStorm 中以调试模式加载启动任务
- python - 向python字典添加值,只返回最后一个值
- mysql - 来自 2 个带变量的表的 SQL 数学函数在一个表中显示输出
- android - 如何在 Youtube 视频的 Android Youtube API 中删除相关视频?
- google-chrome-extension - 是否可以通过 chrome.downloads API 获取整个 http 请求?
- android - 为什么我们需要一个带有 FCM 的推送通知提供程序
- ruby-on-rails - 有没有办法从 config/deploy/ 获取具有角色的服务器列表
.rb - regex - 捕获一组中的重复字符串
- android - 以编程方式设置时,材料设计密码切换效果不起作用
- sql-server - 与单个主键有多个关系的表