栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++的各种输入

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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   //接收的最后一个为'',所以只看到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()直接结束。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/312039.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号