码迷,mamicode.com
首页 > 编程语言 > 详细

C++的字符输入

时间:2014-11-15 20:14:08      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   sp   div   on   

字符串的输入有6中方式,这六种方式各有各的特点,我这篇学习笔记是自己的经验总结,没有去探讨内存,函数库等的复杂问题,仅仅是为了实用:

第一:cin

cin一次接受一个字符,所以有的人会选择定义一个字符型数组,然后用cin循环进行输入,但是cin的局限性是:遇到空格就会停止接受字符;

第二:ch1=cin.get();

作用也是接受一个字符,然后赋值给char类型的ch1,输出ch1;

第三:cin.get(ch2);

作用还是接受一个字符,和第二个一样,只不过形式不同,输出ch2;

第四:cin.get(buff1,6);

这里是cin.get()的第二个用法,参数表里面带有3个参数,第三个参数不写就默认为‘\n’;解释一下,第一个参数是要接受字符的字符串数组Buff1,第二个是要就收的字符的个数+1后的数;

第五:cin.getline(buff1,5,‘s‘)

cin.getline()与cin.get()是差不多的,就是用getline就要包含#include<string>;而且它不把结束字符输出;

第六:getline(cin,str);

最后一个getline(cin,str);解释一下参数表,cin一定要写上去,str这是获取一行后所存放的字符串名称;

 

最后给出一段把六种情况整合在一起的代码:

ps:我的编译器是VS2012


字符串的输入输出
cin
ch1=cin.get();
cin.get(ch2);


cin.get(buff1,6);
cin.getline(buff1,5,‘s‘)
getline(cin,str);
*/
#include<iostream>
#include<string>
using namespace std;
int main()
{
//这两个常数的定义可以放在main外面的
#define N 10
const int S=80;


string str;
char ch1,ch2,ch3,ch4,ch5;
char buff1[S];
char buff2[N][S];


cout<<"Please input a string \n"<<endl;


cin>>buff1[S];
cout<<"By cin\n";
cout<<buff1[S]<<endl<<endl;


ch1=cin.get();
cout<<"By cin.get()\n";
cout<<ch1<<endl<<endl;


cin.get(ch2);
cout<<"By cin.get(ch2)\n";
cout<<ch2<<endl<<endl;


cin.get(buff1,6);
//cin.get()第二个用法,也是输入一行(同cin.getline()),也可以加上第三个参数,和getline一样,但是区别就是,不输出分隔符~
cout<<"By cin.get(buff1,6)\n";
cout<<buff1<<endl<<endl;//要注意这个输出是输出Buff1;


cin.getline(buff1,5,‘s‘);//要注意与getline的区别
//cin.getline()有三个参数:接受字符串m,接受个数5,结束字符
cout<<"By cin.getline(buff1,5,‘s‘)"<<endl;
cout<<buff1<<endl<<endl;


getline(cin,str);
//getline()是定义在<string>中的一个函数,这里的参数表的意思是:cin是必须要有的,str就是得到字符后存放的字符串名称,等一下输出就是输出这个str
cout<<"By getline(cin,str)"<<endl;
cout<<str<<endl<<endl;

system("pause");
return 0;
}

 

C++的字符输入

标签:style   blog   io   color   ar   os   sp   div   on   

原文地址:http://www.cnblogs.com/tianjintou/p/M-Kepler.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!