c++字符串的输入

首先,对于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;

这里写图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值