1
#include <iostream>
int main()
{
    using namespace std;
    char a[50];
    int y;
    cin >> y;
    cin.getline(a, 40); 
    cout << "y= " << y << "\n"<< "a=" << a << endl;
}

When run, I input 45, enter. Then the output is

y= 45
a=

I haven't have a chance to input a. But when I use this code:

#include <iostream>
int main()
{
    using namespace std;
    char a[50];
    int y;
    cin.getline(a, 40);
    cin >> y;
    cout << "y= " << y << "\n" << "a=" << a << endl;
}

I run it with 45, enter, fish, enter. Its output

y= 45
a=fish

So, can anybody explain why cin.getline(a,40) in first code not work, but it work in second code? I got confused.

Mat
  • 188,820
  • 38
  • 367
  • 383
Haha TTpro
  • 21
  • 4
  • Is it not the case that `cin >> someInt` doesn't eat the newline? Try two `getline()`s and `std::stoi()`. Also, use `std::string` for safety reasons. – user3383733 Mar 09 '14 at 15:46
  • @user3383733 I would just do a `cin.clear();`. It seems more simple to me :) – Blue Ice Mar 09 '14 at 15:47
  • possible duplicate of [Why does std::getline() skip input after a formatted extraction?](http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – chris Mar 09 '14 at 15:52

2 Answers2

2

In the first case, the input will still contain a newline, which is then consumed by the following cin.getline() call, which reads to the next newline. The program then terminates.

In the second case, cin.getline() will read the first line until the newline, and then the first integer after that is being read.

Your problem is therefore that cin >> y does not consume your newline character. You can compensate for this by making a second call to cin.getline():

#include <iostream>
int main()
{
    using namespace std;
    char a[50];
    int y;
    cin >> y;
    cin.getline(a, 1);
    cin.getline(a, 40); 
    cout << "y= " << y << "\n"<< "a=" << a << endl;
}
riklund
  • 951
  • 1
  • 7
  • 15
1
#include <iostream>
int main()
{
    using namespace std;
    char a[50];
    int y;
    cin >> y;
    cin.get();
    cin.getline(a, 40); 
    cout << "y= " << y << "\n"<< "a=" << a << endl;
}

I found this, it work. so, just add cin.get() after cin>> y, it will consume \n character.

Thanks everybody have answer my question.

Haha TTpro
  • 21
  • 4