新人对缓存区还是不怎么了解,想请教一下循环中那个cin.get()读取的到底是什么?
我本来以为是getline或者cin输入完会在缓存区留下一个回车,用cin.get()把回车给读取掉。可是我后来试着把getline或者cin注释掉,并且注释掉循环中的cin.get,发现循环都能正常运行,可一旦把这两个都留着只注释掉cin.get,程序运行的就不正常了。
希望有懂的前辈指点一下,谢谢了。
#include "stdafx.h"
#include
#include
#include
const int NUM = 5;
int main()
{
using std::vector;
using std::string;
using std::cin;
using std::cout;
vector<int> ratings(NUM);
vector<string> titles(NUM);
cout << "you will do exactly as told. you willenter\n"
<< NUM << " book titles and your ratings (0-10).\n";
int i, A;
for (i = 0; i < NUM; i++)
{
cout << "enter title #" << i + 1 << ": ";
getline(cin, titles[i]);
cout << "enter your rating : ";
cin >> ratings[i];
cin.get();//就是这个不是很懂
}
cout << "thank you. you entered the following:\n"
<< "rating\tBook\n";
for (i = 0; i < NUM; i++)
{
cout << ratings[i] << "\t" << titles[i] << std::endl;
}
cin.get();
return 0;
}
cin >> ratings[i]; 这句代码让你输入后,你会敲一个回车表示输入完毕。此时在输入流中会有一个换行符,而cin.get()就是用来读取这个换行符的。
如果你只注释掉循环中的cin.get(),那输入流中的换行符就会在第二次循环时对getline()造成影响。
如果你把这两句都去掉,当然输入流中就没有换行符了。getline()是在你输入后丢弃换行符的。
cin >> ratings[i];
cin.get();//就是这个不是很懂
码友,你好:
cin在接受数据的时候会过滤回车
cin.get()会接收回车,以\n存在