1. 程式人生 > 程式設計 >C++ 實現輸入含空格的字串

C++ 實現輸入含空格的字串

1、scanf函式(包含標頭檔案#include <stdio.h>)

scanf函式一般格式為scanf(“%s”,st),但scanf預設回車和空格是輸入不同組之間的間隔和結束符號,所以輸入帶空格,tab或者回車的字串是不可以的。

解決方法如下:

1. 利用格式符“%[]”它的作用為掃描字元集合。

Scanf(“%[^c]”,str); 其中“c”是一個具體的字元常量(包括控制字元)。

當輸入字串時,字元“c”將被當作當前輸入的結束符。

利用此格式符就可以由程式設計者自己指定一個輸入結束符。

例如:

scanf("%[a-z A-Z0-9]",str)表示只匹配輸入是大小寫字母和數字,遇到非數字和字母時輸入結束。

例如:

int main() 
{
 char st[50];
 scanf("%[^\n]",st);// \n作為字串輸入的結束符
 printf("%s",st);
 return 0;
}

2. cin(包含標頭檔案#include <iostream>)

cin是C++中最常用的輸入語句,當遇到空格或者回車鍵即停止。無法解決。

3. gets()

可以無限讀取,以回車結束讀取,C語言中的函式,在C++中執行會產生bug。在C11標準中已被正式刪除,建議不要用!!!

4. getline()(包含標頭檔案#include <string>)

若定義變數為string型別,注意不是字元型陣列。則要考慮getline()函式。

用法如下:

int main() 
{ 
 string st; 
 getline(cin,st); 
 cout<<st<<endl;
 return0; 
}

5.cin.get (char *str,int maxnum)

cin.get()函式可以接收空格,遇回車結束輸入。

int main() 
{ 
 char st[50]; 
 cin.get(st,50); 
 cout<<a<<endl;// 輸出也可以用printf("%s",st); 
 return0; 
}

6.cin.getline (char *str,int maxnum)(包含標頭檔案#include <string>)

cin.getline()函式可以同cin.get()函式類似,也可接收空格,遇回車結束輸入。

int main() 
{ 
 char st[50]; 
 cin.getline(a,50); 
 cout<<a<<endl; // 輸出也可以用printf("%s",st); 
 return0; 
}

7. 字串型別轉換為字元陣列

(a)c_str() 
 char p[50]; 
 string str="I Love Ningbo!"; 
 strcpy(p,str.c_str()); 
 printf("%s",p);
 
(b)data()
 char p[50]; 
 string str="I Love Ningbo!"; 
 strcpy(p,str.data()); 
 printf("%s",p);

補充知識:c++ cin輸入空格

直接新增一行程式碼:

cin >> noskipws;

noskipws

例項:

#include<iostream>
using namespace std;
int main()
{
 cin >> noskipws;//設定cin讀取空白符;
 char c;
 size_t acount =0,ecount =0,icount =0,ocount =0,ucount = 0,scount = 0;
 while (cin >> c)
 {
 if (c == 'a')++acount;
 if (c == 'e')++ecount;
 if (c == 'i')++icount;
 if (c == 'o')++ocount;
 if (c == 'u')++ucount;
 if (c == ' ')++scount;
 }
 cout << "a: " << acount << endl;
 cout << "e: " << ecount << endl;
 cout << "i: " << icount << endl;
 cout << "o: " << ocount << endl;
 cout << "u: " << ucount << endl;
 cout << "space: " << scount << endl;
 return 0;
}

***執行結果:***

C++ 實現輸入含空格的字串

以上這篇C++ 實現輸入含空格的字串就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。