0

我希望用户输入一个字符串,双精度和长整数,但事情是在第一次之后,该字符串有点被忽略并留空并直接提示输入双精度。

这是我的代码:

#include <iostream>
#include <string>

using namespace std;

int main () {
    string name;
    double price;
    long serial;

    cout << "Enter the dvd's name: "; getline(cin, name);
    cout << "Enter the dvd's price (in $): "; cin >> price;
    cout << "Enter the dvd's serial number: "; cin >> serial;

    cout << endl;

    cout << "Enter the dvd's name: "; getline(cin, name);
    cout << "Enter the dvd's price (in $): "; cin >> price;
    cout << "Enter the dvd's serial number: "; cin >> serial;

    return 0;
}

代码控制台

正如你第一次看到的那样,我第二次可以输入一个字符串,只是将我直接发送到双精度,即使我忽略了丢失的字符串,然后输入一个双精度然后长,它会将名称打印为空字符串。

我的代码有什么问题?

4

2 回答 2

1

序列号后面的空格(回车或空格)没有检索,然后将getline其拾取。

编辑:正如 johnathon 指出的那样,cin >> ws在这种情况下不能正常工作(我确信我以前这样使用过,虽然我找不到一个例子)。

经测试的解决方案:相反,在序列号之后添加它会从流中获取回车符(和任何其他空格),以便为下一个 DVD 名称做好准备。

string dummy;
getline(cin, dummy);
于 2012-05-10T17:41:50.827 回答
1

在这种情况下,我通常使用 istringstream(如下所示)。但更好的解决方案是使用 cin.ignore

#include <sstream>

int main () {
    string name,line;
    double price;
    long serial;

    cout << "Enter the dvd's name: "; getline(cin, line);
    name = line;
    cout << "Enter the dvd's price (in $): ";
    getline(cin,line);
    istringstream(line)>>price;
    cout << "Enter the dvd's serial number: ";
    getline(cin,line);
    istringstream(line)>>serial;
    cout << endl;
    return 0;

}

于 2012-05-10T18:49:45.290 回答