Bypassing enter

My doubt is how to read a string in next line followed by an integer like as follows

8
111111110001

we have to read from keyboard 8 as integer and then after pressing enter we have to read 111111110001 as a string .

Below is my code , when i gave input as 8 111111110001 (separated by space) , it works properly but when i press enter , program is not reading string.

Thanks in advance .

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int n;
    string s;
    cin >> n;
    getline(cin,s);
    return 1;
}
Last edited on
because you only cin the n you should cin also the string s like this cin>>n>>s
Last edited on
also i think youre confusing between getline and cin
but if you want to do in you way
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int n;
    string s;
    getline(cin,s,'\n');
    cin >> n;


    return 1;
}
Last edited on
Thank you @justin i am following 2nd one :)
After the user types the integer, the enter key is pressed. All those characters, including the newline character '\n' are stored in the input buffer. After cin >> n that newline still remains in the buffer. We can remove it using cin.ignore().


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int n;
    string s;
    cout << "enter an integer: \n";
    cin >> n;
    
    cin.ignore(1000, '\n'); // remove newline (and any other chars)
                            // from input buffer
    cout << "enter a string: \n";
    getline(cin,s);
    
    cout << "n = " << n << endl;
    cout << "s = " << s << endl;
    
    return 0;
}


@justinelandichoruiz unfortunately you provide a workaround, which merely hides the problem temporarily, rather than a solution.
Last edited on
@chervil can i ask you, what is the purpose of 1000 in the param of cin.ignore?
what is the purpose of 1000 in the param of cin.ignore?


1000 was an arbitrary number I chose. it means, ignore up to 1000 characters from the input stream, or until the delimiter is found, whichever comes first.

See reference:
http://www.cplusplus.com/reference/istream/istream/ignore/
okay i think the reference is enough. thank you

Topic archived. No new replies allowed.