C++的各种输入

各种输入的总结:

  1. cin会在’空格’、‘Tab’、'回车’处截断
string input = "";
cin >> input;

//这时读入一个字符
>>a 2
//这时读入两个字符    
>>a2 b
  1. getline(cin,string)

eg.getline()属于string流,需要include头文件string

string input = "";
getline(cin, input);

//这时读入三个字符
>>a 2
    
可以指定'#'或其他符号为结束字符,这时候敲击‘回车’键,输入不会终止
getline(cin, input,'#');

>>123
78 9#
>>123
78 9
  1. cin.getline(接收字符串数组的名称,接收字符个数,结束字符)

eg.cin.getline()属于istream流,从输入流中获得指定长度字符,赋值给数组或字符指针

char input[100];
cin.getline(input, 3);
cout << input << endl;

///必须为字符串数组  不能为string
>>abcd
>>ab   //接收的最后一个为'\0',所以只看到2个字符输出
  1. cin.get()

eg.与cin.getline()类似,不同之处在于get()函数录入到终止字符后, 控制输入流的指针指在了终止字符,后面的被放在缓冲区,而getline函数()遇到终止字符后指针位置在终止字符后面。

不能将两个cin.get()连用,除非中间添加cin.ignore()

常用cin.get()来读取回车,因为当遇到回车这个终止字符时会停留在这,而cin.getline()则停留在后面的字符

char input[100];
cin.getline(input, 30, '#');
cout << input << endl;
cin.getline(input, 30, '#');
cout << input << endl;

>>This is the first getline.#This is the second getline.#
>>This is the first getline.
This is the second getline.
char input[100];
cin.get(input, 30, '#');
cout << input << endl;
//cin.ignore();
cin.get(input, 30, '#');
cout << input << endl;

>>This is the first get.#This is the second get.#
>>This is the first get.
//
char input[100];
cin.get(input, 30, '#');
cout << input << endl;
cin.ignore();
cin.get(input, 30, '#');
cout << input << endl;    
    
>>This is the first get.#This is the second get.#
>>This is the first get.
This is the second get.
  1. C语言的gets()

eg.读取整行输入,直至遇到换行符,然后丢弃换行符,储存其余字符,并在其末尾添加一个空字符使其成为一个字符串。用时需要include头文件stdio.h

char str[length]; 
gets(str);
  1. getline()函数与cin 混用
int main()
{
	int age;
	string name;
	cout << "请输入年龄:" << endl;
	cin >> age;
	cout << "请输入姓名:" << endl;
	getline(cin, name);
	cout << "年龄:" << age << endl;
	cout << "姓名:" << name << endl;
}
//
请输入年龄:
22
请输入姓名:
年龄:22
姓名:
//添加cin.ignore()
>>请输入年龄:
22
请输入姓名:
yee
年龄:22
姓名:yee

cin>>:流提取运算符根据它后面的变量类型读取数据,从非空白符号开始,遇到Enter、Space、Tab键时结束。并且,cin不会主动删除输入流内的换行符。

getline函数:从istream中读取一行数据,当遇到“\n”时结束返回。

因此,程序执行过程是这样的:

在cin>>age语句获取了年龄之后,把换行符留在了输入流之中;接下来,getline()函数第一个读入的就是cin>>语句未处理的换行符,导致getline()直接结束。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值