读取带空格字符串小结
1 ,gets()
可以無限讀取,以回車結束讀取,C語言中的函數,在C++中運行會產生bug。
如:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
???????? chara[50];
???????? cin>>a;
???????? gets(a);
???????? cout<<a<<endl;
???????? return0;
}
輸入:I love China回車結束輸入,輸出結果為love China。首字符自動丟棄
2 , getline()
若定義變量為string類型,則要考慮getline()函數。用法如下:
#include <iostream>
#include <string>
using namespace std;
int main()
{
???????? stringa;
???????? getline(cin,a);
???????? cout<<a<<endl;
???????? return0;
}
輸入:I love China回車并未結束輸入,需回車兩次才能結束輸入,輸出結果為:I love China.
3 , cin.get? cin.getline
cin.get()函數可以接收空格,遇回車結束輸入。
#include <iostream>
using namespace std;
int main()
{
???????? chara[50];
???????? cin.get(a,50);
???????? cout<<a<<endl;
???????? return0;
}
輸入:I love China回車結束輸入,輸出結果為I love China。
4 , 用scanf()輸入帶有空格的字符串
scanf(“%[^\n]”,str);
下面是具體示例:
#include <stdio.h>
int main()
{
?char a[50];
scanf("%[^\n]",&a);
printf("%s\n",a);
return 0;
}
轉載于:https://www.cnblogs.com/yfz1552800131/p/8629819.html
總結
以上是生活随笔為你收集整理的读取带空格字符串小结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电脑坏了怎么恢复内存(台式电脑内存坏了怎
- 下一篇: flash电脑安装版下载(电脑软件fla