1. 主页 > 2018世界杯阿根廷 >

C++字符串的几种输入方法(string和字符数组)

ps:本文大部分内容参考于这篇博客,在这里加入了自己对这些函数在字符数组和string变量的理解和总结。

C++中的输入大致有6种方法:cin,cin.get(),cin.getline(),gets(),getchar()

1,cin 用法一:最常用的方法,接收一个字符串,无论是string还是char a[10],都是一样,但是遇到“空格”,“TAB”,"回车"都结束。

#include

#include

using namespace std;

int main()

{

string a, b;

cin >> a >> b;

cout << a << endl;

cout << b << endl;

return 0;

}

#include

#include

using namespace std;

int main()

{

char a[10];

cin >> a ;

cout << a << endl;

return 0;

}

遇到空格只读入之前的数据

2,cin.get()

用法一:cin.get(字符变量名)可以用来接收字符

#include

#include

using namespace std;

int main()

{

char ch;

ch = cin.get();//或者是cin.get(ch);

cout << ch;

return 0;

}

用法二:cin.get(字符数组名,接收字符个数),用来接收一行字符串(可以接收空格),这个最大的用途是可以定量的接收字符的个数(但是要注意,如果定义的数组的个数是20,则实际上只能接收19个字符,还要加上'\0')

这个方法只能正针对于是字符数组,不能使用string来输入。

#include

#include

using namespace std;

int main()

{

char a[20];

cin.get(a, 20);

cout << a;

return 0;

}

用法三(直接copy):cin.get(无参数)没有参数主要是用于舍弃输入流中的不需要的字符,或者舍弃回车,弥补cin.get(字符数组名,接收字符数目)的不足,其实质是相当于是getchar();

#include

using namespace std;

int main(void)

{

char arr[10];

cin.get(arr,10);

cin.get();//用于吃掉回车,相当于getchar();

cout<

cin.get(arr,5);

cout<

system("pause");

return 0;

}

输入abcdefghi

输出abcdefghi

输入abcde

输出abcd

请按任意键继续

#include

using namespace std;

int main(void)

{

char arr[10];

cin.get(arr,10);

//cin.get();//用于吃掉回车,相当于getchar(); 现在把这行注释掉试试看

cout<

cin.get(arr,5);

cout<

system("pause");

return 0;

}

输入abcdefghi

输出abcdefghi

请按任意键继续

3,cin.getline() 可以接收空格,并且输出。浅显的用法其实和cin.get()差不多。(也不能使用string来进行输入)

#include

#include

using namespace std;

int main()

{

char a[20];

cin.getline(a, 20);

cout << a;

return 0;

}

更加深层的用法其实就是cin.getline()的原型,这个函数本来有三个参数,分别是字符串的位置,接受个数,结束字符。 如果将例子中cin.getline()改为cin.getline(m,5,'a');当输入jlkjkljkl时输出jklj,输入jkaljkljkl时,输出jk 当用在多维数组中的时候,也可以用cin.getline(m[i],20)之类的用法:

#include

#include

using namespace std;

main ()

{

char m[3][20];

for(int i=0;i<3;i++)

{

cout<<"\n请输入第"<

cin.getline(m[i],20);

}

cout<

for(int j=0;j<3;j++)

cout<<"输出m["<

}

4,getline() 接收一个字符串,可以接收空格并输出,不过要包含#include 这也就弥补了之前cin.getline()和cin.get()的不能读取string的一个小的弊端这里还要将这个写法稍微改正一下getline(cin,字符串数组名);

#include

#include

using namespace std;

int main()

{

string s;

getline(cin,s);

cout << s;

return 0;

}

5,gets() 接收一个字符串,可以接收空格并且输出,需要包含#include 但是这个函数有些奇葩的是,这个函数必须要包含头文件string,但是这个函数却不能直接对变量string来进行赋值。

#include

#include

using namespace std;

int main()

{

char s[10];

gets_s(s);

cout << s;

return 0;

}

这里提一下,这个函数由于不安全,在VS2015及以后的IDE中就不存在这个函数,而是用gets_s()函数来代替。具体的信息请点击这里!

个人感觉这个函数和cin.getline()没啥区别,只不过是cin.getline中多处一个参数。

6.getchar() 获取单个字符,需要包含#include。 这个函数尽量少用

#include

using namespace std;

main ()

{

char ch;

ch=getchar(); //不能写成getchar(ch);

cout<

}

最后来一个各个函数对变量string的输入的总结:

在解决一些ACM的算法题的时候,可以尽量的使用字符数组。一般我更加偏好于使用getline()函数,毕竟对各个类型的字符串都兼容。