簡體   English   中英

輸入句子並將其轉換為字符串

[英]inputting sentence and turning it into string

int main(void)

{
char x[20];
cout << "enter a C string:";
cin >> x;
cout << x << endl;
return 0;
}

我知道cin在讀取所需類型的數據時會跳過所有前導空格,直到看到下一個空格為止。 因此,如果我鍵入“ abc school”,則僅將“ abc”讀入x。 如果我希望將整個句子讀入x怎么辦?

在標准庫中使用getline 該網站是您的朋友。

最好的解決方案是使用getline,並將x的數據類型更改為字符串:

#include <iostream>
using namespace std;
int main(void)

{
string x;

cout << "enter a C string:";
getline(cin,x);

cout << x << endl;
return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM