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

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章