2017-04-09 132 views
2
#include <iostream> 
#include <string> 
#include "Friend.h" 
#include "Address.h" 

using namespace std; 

int main() { 
    string name = ""; 
    string street = ""; 
    string city = ""; 
    string state = ""; 
    long phone_number = 0000000000; 
    int zip_code = 00000; 
    int feet = 0; 
    int inches = 0; 

    cout << "What is your friends name: "; 
    cin >> name; 

    cout << "What street does he live on: "; 
    cin >> street; 

    cout << "What city does he live in: "; 
    cin >> city; 

    cout << "What state does he live in: "; 
    cin >> state; 

    cout << "What is his 10 digit phone number: "; 
    cin >> phone_number; 

    cout << "What is his zip code: "; 
    cin >> zip_code; 

    cout << "How tall is he in feet: "; 
    cin >> feet; 
    cout << "And how many inches: "; 
    cin >> inches; 

    return 0; 
} 

這是我的代碼。這裏的問題是:輸入我的電話號碼後,它不再等待輸入。它會自動輸出cout <<語句,然後自行終止它。我不知道爲什麼會發生這種情況。`cin >>變量`不等待輸入

有人可以幫我嗎?

+0

我猜你正在輸入電話號碼部分的空格。當這樣做時,cin將每個值作爲輸入。所以如果你輸入'0 123 4567',電話號碼是0,zip_code是123,腳是4567 ... –

+0

你從不檢查你的I/O操作的返回值。如果*你*不關心你的程序的正確性,我們應該怎麼知道什麼是錯的? –

回答

4

變量phone_number是long類型,與long int相同。這意味着您只能輸入數字作爲phone_number的輸入。

爲什麼它不適用於您的最佳猜測是您輸入的電話號碼爲:XXX-XXXXXXX(帶短劃線)。 "-"分割輸入,並將破折號後面的數字傳遞給下一個輸入變量zip_code

如果你嘗試輸入電話號碼爲:1234567890,那麼它工作正常。如果您想使用短劃線,則考慮更改phone_number以鍵入string

至於使用您的字符串類型變量的一邊,接受輸入getline()而不是cin <<使編譯器將繼續閱讀所有輸入直到ENTER鍵擊。