首先,对于cin我们需要知道,它是通过空白(空格、制表符、换行符)来确定结束位置的。所以当我们输入一串单词例如:jon snow的时候,只会读取第一个单词,后面的单词则放在输入队列中。
{
char name[20];
char dessert[20];
cout << “Enter your name:” << endl;
cin >> name;
cout << “Enter your favorite food: ” << endl;
cin >> dessert;
cout << “I have some delicious ” << dessert << ” for you ” << name << endl;
}
输出结果:
出现如此的结果和cin的特点有关,为了避免这种情况,一般采用cin.getline()和cin.get()来解决:
1.getline() 读取整行,通过回车输入的换行符来确定输入结束,但是不会保存换行符在输入队列中:
所以小改上面的代码:
int main()
{
char name[20];
char dessert[20];
cout << "Enter your name:" << endl;
cin.getline(name, 20);
cout << "Enter your favorite food: " << endl;
cin.getline(dessert, 20);
cout << "I have some delicious " << dessert << " for you " << name << endl;
return 0;
}
输出:
可以看出能够达到预期。
同样cin.get()也有同样的功能,但是他不会读取和丢弃换行符,也就是说将上面的getline替换成get的话,会出现输入第二个字符串dessert的时候会发现输入队列中的换行符,这时候会判定输入结束,所以输出结果不会显示food.
解决的方法就是再第一次输入之后用cin.get()来读取换行.
int main()
{
char name[20];
char dessert[20];
cout << "Enter your name:" << endl;
cin.get(name, 20);
cin.get();
cout << "Enter your favorite food: " << endl;
cin.get(dessert, 20);
cout << "I have some delicious " << dessert << " for you " << name << endl;
return 0;
}
所以以上两种方法都可以解决多单词的输入。
但是,如果想要读取换行输入呢?即,在输入名字的时候敲回车,然后想要继续输入dessert。
可以看到程序直接结束。
首先介绍输入的几种状态:
ios::goodbit 值是0 无错误
ios::eofbit 值是1 已到达文件尾
ios::failbit 值是2 失效位
ios::badbit 值是4 错误输入
获得输入的状态:cin.rdstate()
int a;
cin >> a;
cout << cin.rdstate() << endl;
if (cin.rdstate() != ios::goodbit)
{
cout << "wrong input" << endl;
}
输出结果:
可以看出输入除了有输入流之外还有一个输入状态的东西,来表示当前输入是否正确。
而,cin.get()会在读取到换行符的时候将输入状态设置为ios::failbit。
所以,要想想要输入换行而不让输入终止,需要清除输入状态和输入数据流。分别用到cin.clear()和cin.sync()
char name[20];
char dessert[20];
cout << "Enter your name:" << endl;
cin.get(name, 20);
cin.clear();
cin.sync();
cout << "enter your favorite food: " << endl;
cin.get(dessert, 20);
cout << "i have some delicious " << dessert << " for you " << name << endl;
验证get函数读取换行时将状态设置为了ios::failbit
cout << ios::goodbit << " " << ios::eofbit << " " << ios::failbit << " " << ios::badbit << endl;
cout << "Enter your name:" << endl;
cin.get(name, 20);
cout << "before clear:" << cin.rdstate() << endl;
cin.clear();
cout << "after clear:" << cin.rdstate() << endl;
cin.sync();
cout << "enter your favorite food: " << endl;
cin.get(dessert, 20);
cout << "i have some delicious " << dessert << " for you " << name << endl;