anshabhi
anshabhi

Reputation: 423

Unable to read two strings with cin.get()

sample executionWhy does trying to input two strings using cin.get() fails? I can successfully read the first string but the input fails for second string and subsequent operations.. See the code:

#include <iostream>
#include <stdlib.h>

int main(){
long int n,k;
char a[11],b[11];
cin.get(a,11);

n = atoi(a);

cin.get(b,11);
cout<<b;   
k = atoi(b);


cout      << "\ncin.rdstate(): " << cin.rdstate()
      << "\n    cin.eof(): " << cin.eof()
      << "\n   cin.fail(): " << cin.fail()
      << "\n    cin.bad(): " << cin.bad()
      << "\n   cin.good(): " << cin.good() << endl << endl;
}

I am trying to input two strings and store them into long int variables as shown in program, but the cin.get(b,11) fails and stack overflow occurs for k= atoi(b) .Also, you may observe nothing is output for cout<<b .. And, at last cin.fail() is set to 1 , which means I am doing some kind of logical error.. Please help me in rectifying this! Please suggest some method which is fast and meant for c++ only .. (If you feel this question is too bad please mention in comments before down voting this, I am already struggling at 21 rep!)

Upvotes: 1

Views: 2411

Answers (2)

Roman Kutlak
Roman Kutlak

Reputation: 2784

cin.get() Does not extract the delimiter from the input (documentation).

If you are C++ with streams it makes sense to use the built in functionality. In particular, C++ offers formatted I/O. To read two numbers you should use:

long int a, b;
cin >> a;
cin >> b;

This will read two numbers from the standard input.


If speed is a concern, try to turn off C I/O synchronisation: std::ios::sync_with_stdio(false); There is an interesting benchmark here that shows that if you turn of synchronisation with C I/O, streams are actually pretty fast.

Upvotes: 1

Praveen Kumar
Praveen Kumar

Reputation: 378

\n will remain in the buffer after the first cin. You can solve this problem by adding an empty cin.get()

cin.get(a,11);
n = atoi(a);
cin.get();
cin.get(b,11);
cout<<b;   
k = atoi(b);

Upvotes: 3

Related Questions