提问人: 提问时间:12/28/2021 更新时间:12/29/2021 访问量:167
C++ 将 cin.getline 值存储到 double 变量和 char 变量 [duplicate]
C++ store cin.getline value to double variable and to char variable [duplicate]
问:
在我的程序中,我想限制用户可以使用 输入的数字数量。我的代码看起来像这样(这不是整个代码):cin.getline(variable, N)
#include <iostream>
int main()
{
input:
long double num1;
long double num2;
long double result;
char response;
cout << "Enter first number and then press enter" << endl;
cin >> num1;
cout << "Enter + to add, - to substract, * to multiply, / to divide, v to find the sqare root and ^ to find the power" << endl;
cin.getline(response, 2); //Here is the problem!
}
当我运行它时,我收到以下错误:
如何将返回的值存储到 a 和 a 变量中?cin
double
char
如果您想了解更多信息,请告诉我。
更新:我为我的项目找到了不同的解决方案。该解决方案特定于我的代码,在其他情况下不起作用,因此上传它毫无意义。感谢您抽出宝贵时间接受采访。
答:
-2赞
digito_evo
12/28/2021
#1
您无法使用 cin.getline 获取数字。取而代之的是获取字符缓冲区,然后将其转换为双精度。
#include <iostream>
int main()
{
input:
long double num1;
long double num2;
long double result;
char response[3] { }; // resonse should be able to take in 3 chars (2 + 1 for '\0')
cout << "Enter first number and then press enter" << endl;
cin >> num1;
cout << "Enter + to add, - to substract, * to multiply, / to divide, v to find the sqare root and ^ to find the power" << endl;
cin.getline(response, 2);
}
然后,你可以使用 std::strtold
将任何字符串缓冲区 () 转换为 .char*
long double
评论
0赞
digito_evo
12/28/2021
@xDev120 上面有什么?input:
0赞
12/28/2021
它是代码后面的 goto 的标签
0赞
JHBonarius
12/28/2021
这太可怕了。为什么只使用 10 个字符的缓冲区?为什么要使用 char 数组???然后从中构造一个字符串并转换为长双精度??看看打印的行前面说了什么:它需要一个“+”、“-”或这样的字符,而不是一个数字。
0赞
sweenish
12/28/2021
为什么要尝试将运算符字符转换为双精度符?你为什么要将 C 字符串转换为? 是你想要的。std::string
std::atof()
0赞
digito_evo
12/29/2021
@JHBonarius 请检查更新后的答案。
评论
cin >> response;
就像你已经用 做了一样,但它会读出左边的 ,所以你必须在 之间添加一个: godbolt.org/z/9Yo5bxx6adouble
<enter>
cin >> num1;
cin.ignore();