c++中字符串输入注意的问题

字符串输入

字符串输入时,一般我们可以 cin >> 字符数组; 以空白字符作为输入结束标记。

例如:cin >> str;

输入hello ,终端会显示hello

当你输入hello world,终端也只显示hello,因为遇到空白字符时结束了输入。

如果我们要输入一行字符串,并且带有空白字符时,需要用以下的输入方式

*cin.getline(字符数组名,数组规模);

*cin.get(字符数组名,数组规模);

他们的结束以回车字符或者到达数组规模为止

区别:getline将换行符丢弃,get将换行符留给下一次输入。

可能用文字没有说的太清楚,下面用程序来说明一下。

一.cin >> str[20] 输入

1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     char str1[20],str2[20],str3[20];
 8     char str4[20],str5[20];
 9 
10     cin >> str1;
11 //  cin.get(str2,20);
12 //  cin.get(str3,20);
13 //  cin.getline(str4,20);
14 //  cin.getline(str5,20);
15 
16     cout << str1 << endl;
17 //  cout << str2 << endl;
18 //  cout << str3 << endl;
19 //  cout << str4 << endl;
20 //  cout << str5 << endl;                                             
21 

二.用cin.get();输入

1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     char str1[20],str2[20],str3[20];
 8     char str4[20],str5[20];
 9 
10 //  cin >> str1;
11     cin.get(str2,20);
12     cin.get(str3,20);
13 //  cin.getline(str4,20);
14 //  cin.getline(str5,20);
15 
16 //  cout << str1 << endl;
17     cout << str2 << endl;
18     cout << str3 << endl;                                             
19 //  cout << str4 << endl;
20 //  cout << str5 << endl;
21 
22 }

结果

zztsj@tsj:~/src$ g++ getline.cpp -o test4
zztsj@tsj:~/src$ ./test4
hello world!
hello world!


get将换行符留给了下一次输入,所以str3中就是以换行字符,如果想在str3中也进行输入,需要加入再加一句cin.get(); 这个get就接收了换行字符,str3就可以继续输入了

如下

1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     char str1[20],str2[20],str3[20];
 8     char str4[20],str5[20];
 9 
10 //  cin >> str1;
11     cin.get(str2,20);
12     cin.get();                                                        
13     cin.get(str3,20);
14 //  cin.getline(str4,20);
15 //  cin.getline(str5,20);
16 
17 //  cout << str1 << endl;
18     cout << str2 << endl;
19     cout << str3 << endl;
20 //  cout << str4 << endl;
21 //  cout << str5 << endl;
22 
23 }

三.用cin.getline输入

1 #include<iostream>
 2  
 3 using namespace std;    
 4  
 5 int main()              
 6 {
 7     char str1[20],str2[20],str3[20];
 8     char str4[20],str5[20];
 9     
10 //  cin >> str1;        
11 //  cin.get(str2,20);   
12 //  cin.get();          
13 //  cin.get(str3,20);   
14     cin.getline(str4,20);
15     cin.getline(str5,20);
16     
17 //  cout << str1 << endl;
18 //  cout << str2 << endl;
19 //  cout << str3 << endl;
20     cout << str4 << endl;
21     cout << str5 << endl;                                             
22  
23 }
~                       

结果如下

zztsj@tsj:~/src$ g++ getline.cpp -o test4
zztsj@tsj:~/src$ ./test4
hello world
shanghai  
hello world
shanghai

  

原文地址:https://www.cnblogs.com/tanshengjiang/p/14228601.html