当我尝试输入输入时,我的代码结果为0

时间:2016-09-02 02:30:03

标签: c++ eclipse

//============================================================================
// Name        : Lab02.cpp
// Author      : Insert name
// Version     :
// Copyright   : 
// Description : Hello World in C++, Ansi-style
//============================================================================
/*
 * Write a program that displays
 * First and last name on one line
 * Address on the nest line
 * writes your city, state, zip on next line
 * writes telephone number on the next line
 *
 * Example: First Last
 *          123 Street Avenue
 *          City, Ca. Zipcode
 *          (925)555-5555
 */
#include <iostream>
#include <string>
using namespace std;

int main() {

    long double fullName;
    unsigned int address;
    string cityZip;
    unsigned int phoneNumber;

    cout << "Please enter you full name" << endl;
    cin >> fullName;
    cout << fullName << endl;

    cout << "Enter your address" << endl;
    cin >> address;
    cout << address << endl;

    cout << "Please enter your city, zipzode, and state" << endl;
    cin >> cityZip;
    cout << cityZip << endl;

    cout << "Enter your phone number" << endl;
    cin >> phoneNumber;
    cout << phoneNumber << endl;


    return 0;
}

这是控制台输出

Please enter you full name
first last
0
Enter your address
0
Please enter your city, zipzode, and state

Enter your phone number
0

我的代码一直输出0并且不让我完成输入代码提示的内容。有人能告诉我我做错了什么吗?我应该使用GetLine而不是字符串吗?

1 个答案:

答案 0 :(得分:2)

long double fullName;

cout << "Please enter you full name" << endl;
cin >> fullName;

long double是一个数值。您正在提示输入数值。您可以在此处努力输入名称,但由于该值为long double,因此显然不会起作用。

输入解析失败会使std::cin进入失败状态,所有后续输入操作将立即失败,从而导致您观察到的输出。

总结:

  1. 修复所有变量的类型。它们应该是std::string s。

  2. 使用std::getline()输入一行文字。 operator>>解析单个以空格分隔的工作。每次提示时,您的意图是阅读整行文本,可能包含空格。 operator>>将停止在第一个空间阅读。