簡體   English   中英

如何從C ++中的控制台讀取字符?

[英]How to read character from console in c++?

我正在努力從c ++中的控制台讀取字符。 這是我嘗試做的事情:

char x;
char y; 
char z;

cout<<"Please enter your string: ";
string s;
getline(cin,s);
istringstream is(s);

is>> x >> y >> z;

問題是,如果用戶輸入類似“ 1 20 100”的內容:

x will get 1
y will get 2
z will get 0

我想得到的是x = 1; y = 20; z = 100;

有人有建議嗎?

您不想讀取字符,但要讀取整數。

int x;
int y; 
int z;

cout<<"Please enter your string: ";
string s;
getline(cin,s);
istringstream is(s);

is>> x >> y >> z;

你快到了 operator>>()是格式化的提取運算符。 將變量從char類型更改為int類型,就可以了。

聽起來您想讀取整數。 您可以這樣做:

int x, y, z;

cout << "Please enter three integers: ";
cin >> x >> y >> z;

得到這些結果的原因是,由於x,y和z是字符,因此當您使用istringstream時,它會將第一個字符讀入x,它跳過空格並將字符'2'讀入y,下一個字符是'0 '然后進入z。

char x, y, z;
cout << "Please enter three integers: ";
cin >> x >> y >> z;

如果那不起作用,請使用ints,因為試圖找到一種使用char而不是int來節省內存的解決方法正在擔心這里的錯誤。

暫無
暫無

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

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