gpt4 book ai didi

c++ - 接受第一个字符串输入然后忽略其余的

转载 作者:行者123 更新时间:2023-11-28 03:37:15 25 4
gpt4 key购买 nike

我希望用户输入一个字符串,double 和 long,但问题是在第一次之后,字符串有点被忽略并留空并直接提示输入 double。

这是我的代码:

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

the console of the code

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

我的代码有什么问题?

最佳答案

我一般在这种情况下使用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;

关于c++ - 接受第一个字符串输入然后忽略其余的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10539265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com