`cin >> variable` doesn't wait for input

时间:2017-04-09 23:46:33

标签: c++

#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;
}

This is my code. The problem here is: after I enter my phone number, it just doesn't wait for an input any more. It will output the cout << statements that follow automatically and then terminate it self. I am not sure why this happens.

Could someone help me please?

1 个答案:

答案 0 :(得分:4)

The variable phone_number is of type long, which is the same as long int. This means that you can only enter numbers as input for phone_number.

The best guess why it doesn't work for you is that you enter the phone number as: XXX-XXXXXXX (with the dash). The "-" splits the input, and the numbers after the dash are passed on to the next input variable zip_code.

If you try input for phone number as: 1234567890, then it works fine. If you want to use the dash, then consider changing phone_number to type string.

As an aside, take input for your string-type variables using getline() instead of cin << so that the compiler will continue reading all input until the ENTER key is hit.