C++输入带空格字符串

cin与scanf一样也是遇见空格、制表符、换行符就会分割字符串,所以它无法输入带有空格的字符串。

借用了CS生的代码:

第一段代码:

#include <iostream>
using namespace std;

int main() {
	char str[20];
	cout<<"Enter a string by cin.get():";
	cin.get(str, 20); // input: C C++
	cout<<"received by cin.get():"<<str<<endl;

	cout<<"Enter a string by cin.getline():";
	cin.getline(str, 20);
	cout<<"received by cin.getline():"<<str<<endl;

	return 0;
}

 运行结果:

Enter a string by cin.get():C C++
received by cin.get():C C++
Enter a string by cin.getline():received by cin.getline():

 第一段代码cin.getline(str, 20);行遇到空格了,所以啥也没输入。

第二段代码:

#include <iostream>
using namespace std;

int main() {
	char str[20];
	cout<<"Enter a string by cin.get():";
	cin.getline(str, 20); // input: C C++
	cout<<"received by cin.get():"<<str<<endl;

	cout<<"Enter a string by cin.getline():";
	cin.get(str, 20); // input: C C++
	cout<<"received by cin.getline():"<<str<<endl;

	return 0;
}

运行结果:

Enter a string by cin.get():C C++
received by cin.get():C C++
Enter a string by cin.getline():C C++
received by cin.getline():C C++

实际上,cin.get() 和 cin.getline() 都会遇到换行符并停止读取。问题出在对输入缓冲区的处理上。

在使用 cin.get() 读取字符串时,它会读取指定数量的字符,并将换行符留在输入缓冲区中。这意味着下一个输入操作(例如 cin.getline())会继续从换行符开始读取,导致输入错误。

换行符在输入中起到两个作用:

  1. 实现换行操作:当我们在终端或命令行中输入换行符时,它会告诉程序我们已经输入完一行内容,可以进行下一行的输入。

  2. 留在输入队列中:换行符会留在输入缓冲区中,等待下一个输入操作。这意味着,如果我们使用 cin.get() 或 cin.getline() 来读取字符串,它们会遇到换行符并停止读取。这是因为默认情况下,cin.get() 和 cin.getline() 都会读取输入缓冲区中的字符,直到遇到换行符为止。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值