char 数组的 cin 和 cin.get() 之间的区别
我有这两个代码:
char a[256];cin>>a;cout<
和
char a[256];cin.get(a,256);cin.get();cout<
也许,相对于第二个没有 cin.get();
char a[256];cin.get(a,256);cout<
我的问题是(第一个):对于 char 数组,我应该使用什么?cin 还是 cin.get()?我为什么要使用 cin.get();我的 char 初始化后没有参数?
我的第二个问题是:我的 c++ 老师教我每次使用 cin.get() 初始化字符,并在每次初始化 char 数组或 int 数组或只是 int 或其他任何时间后,再次放入 cin.get();在它之后.这就是我最初想问的.
所以,现在我得到了这 2 个:在这种情况下,整数初始化后没有 cin.get() ,我的程序将中断,我不能再做我的 char 初始化.
int n;cin>>n;字符 [256];cin.get(a,256);cin.get();//有或没有 cin.get();?cout<
还有一个正确的:
int n;cin>>n;cin.get();字符 [256];cin.get(a,256);cin.get();//再次,有还是没有?cout<
那么,怎么了?请有人解释每个案例!谢谢.
解决方案他们做不同的事情,所以选择你想要的,或者下面给出的更好的选择.
第一个 cin>>a;
读取单个单词,跳过任何前导空格字符,并在遇到空格字符(包括行尾)时停止.p>
第二个 cin.get(a,256);cin.get();
读取一整行,然后使用行尾字符,这样重复此操作将读取下一行.cin.getline(a,256)
是一种稍微简洁的方法.
第三个 cin.get(a,256)
读取一整行,但将行尾字符留在流中,因此重复此操作不会提供更多输入.
在每种情况下,如果输入的单词/行长于固定大小的缓冲区,您都会遇到某种不良行为.因此,您通常应该使用更友好的字符串类型:
std::string a;std::cin >>一个;//一个字std::getline(std::cin, a);//整行
字符串会增长以适应任何数量的输入.
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.
解决方案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.
相关文章