문제

I tried to get a string as an input with cin and it worked, but when I tried to get an int as an input just after the string the console won't ask for it and the program shuts down. Here's my code:

#include <iostream>
#include <string>
using namespace std;

void main(void)
{ 
string a, b;
int c, d, e;

cout << "Enter two words \n";
cin >> a, b; 
cout << "Enter three int";
cin >> c, d, e;
cout << c*d;
}

This code won't let me enter the second input, but I can see the second output before the program shuts down.

도움이 되었습니까?

해결책

Your code is wrong:

cin >> a, b;

will not give you what you expect. In you need to read to strings from cin, use:

cin >> a;
cin >> b;

The same applies for the other types.

Also note that:

void main( void )

is not correct. main must return an int:

int main( void )
{
    return 0;
}

다른 팁

The line cin >> a, b; uses the comma operator which evalutes the different expressions from left to right. The result is the same as the following code:

cin >> a;
b;

When the line cin >> c, d, e; is reached, it is similarly evaluted as:

cin >> c;
d;
e;

The result is that when the second cin >> ... statement is evaluted the second word you entered is still in the input buffer it completes without waiting for more input from the user.

This is wrong:

cin >> a, b; 

It should be:

cin >> a >> b; 

Likewise:

cin >> c, d, e;

should be:

cin >> c >> d >> e;

Make sure you enable compiler warnings in future - that way the compiler can point out many simple mistakes like this for you. When I compile your original code with warnings enabled I get:

$ g++ -Wall junk.cpp
junk.cpp:5:1: error: 'main' must return 'int'
void main(void)
^~~~
int
junk.cpp:13:11: warning: expression result unused [-Wunused-value]
cin >> c, d, e;
          ^
junk.cpp:11:11: warning: expression result unused [-Wunused-value]
cin >> a, b;
          ^
junk.cpp:13:14: warning: expression result unused [-Wunused-value]
cin >> c, d, e;
             ^
3 warnings and 1 error generated.

From this it's easy to see that there is something wrong with the two cin lines, and that you also need to change the return type of main to int.

Try with:

int main(void)
{ 
string a, b;
int c, d, e;

cout << "Enter two words \n";
cin >> a >> b; 
cout << "Enter three int";
cin >> c >> d >> e;
cout << c*d;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top