CIN 双精度和不带空格的字符串会导致错误

cin double and string without space results in error

本文关键字:字符串 错误 空格 双精度 CIN      更新时间:2023-10-16

以下程序在 Mac Mojave (AppleClang 10.0.1.10010046( 上输出Error例如输入10cm时(请注意,值和字符串输入之间没有空格(。相同的输入在 Ubuntu 16.04 (GNU 5.4.0( 下工作 (输出:Working(。

int main() {
double val {0.0};
string unit {" "};
cout << "Enter a double value followed by a unit (cm , m, in, ft) with or without a space in between (followed by 'Enter'):n";
if (cin >> val)
{
cout << "Working val" << 'n';
if (cin >> unit)
{
cout << "Working unit" << 'n';
}
else
{
cout << "Error unit" << 'n';
auto f = cin.fail();
auto b = cin.bad();
cout << "f: " << f << ", b: " << b << 'n';
}
}
else
{
cout << "Error val" << 'n';
auto f = cin.fail();
auto b = cin.bad();
cout << "f: " << f << ", b: " << b << 'n';
}
return 0;
}

为什么cin在Mac OS下会进入糟糕的状态?

以下是Mac OS下的完整输出:

Enter a double value followed by a unit (cm , m, in, ft) with or without a space in between (followed by 'Enter'):
10cm
Error val
f: 1, b: 0
Process finished with exit code 0

当我输入例如10 cm(带有空格(时,它正在工作:

Enter a double value followed by a unit (cm , m, in, ft) with or without a space in between (followed by 'Enter'):
10 cm
Working val
f: 0, b: 0
Working unit
f: 0, b: 0
Process finished with exit code 0

编辑:以前的(完整(问题:我正在尝试使用C++进行编程原理和实践中第 4 章的练习 7

:更改循环的主体,使其每次只读取一个双精度。定义两个变量来跟踪到目前为止您看到的最小值和最大值。每次通过循环写出输入的值。如果它是到目前为止最小的,请在数字后面写下到目前为止最小的。如果它是到目前为止最大的,请在数字后面写下迄今为止最大的。

向输入的每个双精度值添加一个单位;即,输入 10 厘米、2.5 英寸、5 英尺或 3.33 米等值。接受四个单位:厘米、米、英寸、英尺。假设换算系数为 1m == 100cm, 1 英寸 == 2.54 厘米, 1 英尺 == 12 英寸。将单位指示器读入字符串。您可以考虑 12 m(数字和单位之间有空格(相当于 12m(没有空格(。

#include "std_lib_facilities.h"
bool legalUnit(string unit)
{
if (unit == "cm" || unit == "m" || unit == "in" || unit == "ft")
{
return true;
}
else {
return false;
}
}

int main() {
bool first {true};
double val {0.0};
double smallest {0.0};
double largest {0.0};
string unit {" "};
cout << "Enter a double value followed by a unit (cm , m, in, ft) with or without a space in between (followed by 'Enter'):n";
while (cin >> val >> unit)
{
if (legalUnit(unit))
{
cout << val << unit << 'n';
if (first == true)
{
first = false;
smallest = val;
largest = val;
}
else if (val < smallest)
{
cout << " the smallest so far.n";
}
else if (val > largest)
{
cout << " the largest so far.n";
}
}
}
return 0;
}

该程序在 mac 和 Linux 上编译没有问题,并输入一个数字,后跟空格和一个单位,例如10 in工作。

现在谈谈我的问题:在 Mac 上,例如,如果我输入10in程序会立即退出,因为cin >> val >> unit返回 false。在 Linux 上,相同的输入工作,这意味着进入循环。

关于编译器,我需要考虑什么吗?我正在使用 Mac Mojave 10.14.5 和 Ubuntu 16.04 的默认设置(自动检测编译器(的 CLion。

Mac 上的某人可以确认10cm等输入不起作用吗?

这是libc ++中的一个错误(我可能会在2013年报告

(。如果在输入流中,数字后跟一个字母,中间没有空格,则读取此数字可能会失败,也可能不会失败,具体取决于字母。"坏"字母是 A 到 F、I、N、P 和 X(以及它们的小写对应字母(。

精明的读者会注意到,这些正是可以构成十六进制常量的字母(是的,P是其中之一(以及单词NAN和INF。

其他行为相同的字符包括加号、减号和小数点(原因很明显(。