Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

c++ - Difference between cin and cin.get() for char array

I have these 2 codes:

char a[256];
cin>>a;
cout<<a;

and

char a[256];
cin.get(a,256);cin.get();
cout<<a;

and maybe, relative to the second one without cin.get();

char a[256];
cin.get(a,256);
cout<<a;

My question is (first one) : for a char array, what should i use? cin or cin.get()? And why should i use cin.get(); with no parameter after my char initialisation?

And my second question is: my c++ teacher taught me to use every time cin.get() for initialisation chars and AFTER every initialisation char array or int array or just int or whatever, to again put cin.get(); after it. That's what i wanted to ask initially.

So, now i got these 2: In this case, without cin.get() after the integer initialisation, my program will break and i can't do anymore my char initialisation.

int n;
cin>>n;
char a[256];
cin.get(a,256); cin.get();  // with or without cin.get();?
cout<<a;

And the correct one:

int n;
cin>>n; cin.get();
char a[256];
cin.get(a,256); cin.get(); // again, with or without?
cout<<a;

So, what's the matter? Please someone explain for every case ! Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They do different things, so choose whichever does what you want, or the better alternatives given below.

The first cin>>a; reads a single word, skipping over any leading space characters, and stopping when it encounters a space character (which includes the end of the line).

The second cin.get(a,256);cin.get(); reads a whole line, then consumes the end-of-line character so that repeating this will read the next line. cin.getline(a,256) is a slightly neater way to do this.

The third cin.get(a,256) reads a whole line but leaves the end-of-line character in the stream, so that repeating this will give no more input.

In each case, you'll get some kind of ill behaviour if the input word/line is longer than the fixed-size buffer. For that reason, you should usually use a friendlier string type:

std::string a;
std::cin >> a;              // single word
std::getline(std::cin, a);  // whole line

The string will grow to accommodate any amount of input.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...