当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - After a integer data type and consecutive two character type. The 2nd character data type skips....Why?

问题描述:

#include<iostream>

using namespace std;

int main()

{

int n=0;

char name[20];

char address[50];

cout<<"Enter a Number";

cin>>n;

cout<<"Enter a Name ="; // HERE

gets(name);

cout<<"Enter a Address=";

gets(address);

cout<<"Number ="<<n<<endl;

cout<<"Name = "<<name<<endl;

cout<<"Address = "<<address<<endl;

}

It has one Integer type and two array of char type..when the program reach at ("Enter a name") why the compiler skip it without showing any problem.

网友答案:

Here's a slightly modified code :

#include<iostream>
#include<cstdio>
using namespace std;
int main(){
int n=0;
char name[20],c;
char address[50];
cout<<"Enter a Number";
cin>>n;
c = getchar();
cout<<"Enter a Name =";
gets(name);
cout<<"Enter a Address=";
gets(address);
cout<<"Number ="<<n<<endl;
cout<<"Name = "<<name<<endl;
cout<<"Address = "<<address<<endl;
}

Here, I have only performed one modification : taking a character input after the number is entered. This character stores the \n or the Enter you press after typing the input. Earlier, the Name field stored the \n and hence input skipped to the next field, but now we have used a buffer character to store it.

网友答案:

Because when you use cin to get the integer, the newline you press to end the input is left in the input buffer, so when you next get a line the gets function will see this newline and read it as an empty line.

You can ask cin to ignore input until (and including) next newline with

cin.ignore(numeric_limits<streamsize>::max(), '\n');
分享给朋友:
您可能感兴趣的文章:
随机阅读: