A Simple input/output query of C++ -


i have take input:

3
sam
99912222
tom
11122222
harry
12299933

so, wrote down following code:

string s; int num,n; cin>>n; while(n--){     getline(cin,s);     cin >> num;     cout << "s=" << s << " num=" << num << endl; } 

so, expected output should be:

s=sam num=99912222
s=tom num=11122222
s=harry num=12299933

but output is:

s= num=0
s= num=0
s= num=0

where did wrong?

one problem cin>>n; statement count leaves newline in input buffer. when call getline see newline , think entered empty line.

then gets worse when try read number, next text not number, it's name, , trying read number set failbit.

a standard solution ignore characters until newline, skip rest of line including newline character. like

std::cin >> n; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

you of course need after other input too.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -