[英]Reading from cin doesn't return entire input string
我必須使用兩個單獨的輸入提示用戶輸入他們的姓名和身高,一個是英尺,一個是英寸。 然后我必須顯示他們輸入的內容。 例如:姓名,您身高 x 英尺 y 英寸。 我編寫的程序可以運行,但沒有按預期運行。 在我為第一個問題(即名稱)編寫輸入后,程序會跳過其他問題並結束程序。
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int name;
int f;
int i;
// Start: Enter Name
cout << "What is your name?" << endl;
cin >> name;
// Enter height
cout << "How many feet tall are you tall?" << endl;
cin >> f;
// Enter inches
cout << "How many inches tall are you after feet?" << endl;
cin >> i;
// End: All info entered
cout << name << " you are " << (f) << " feet " << (i) << " inches tall." << endl;
system("pause");
return 0;
}
首先也是最重要的是,您應該將name
的類型從int
更改為string
。 您當前的程序嘗試讀取你的輸入name
為數字而不是文本。
現在,如果按預期的計划仍然沒有工作,確保當你在輸入打字name
沒有空格(空格,制表符等)在你試圖輸入名稱之間。 例如, John
的輸入可以,但John Smith
不行。 這是因為>>
運算符與cin
值一起使用時,所有空格都相同。 這意味着按下空格鍵與按下程序的回車鍵是一樣的。 如果您嘗試輸入全名,請考慮使用getline
讀取輸入,直到按下 Enter 鍵。
Getline 示例:
cout << "What is your name?";
getline (std::cin,name);
摘要:更改int name;
到string name;
. 如果您需要為名稱讀取多個單詞,請使用getline
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.