C++ 中带有尾随字符的数字输入
Numeric input in C++ with trailing chars
我需要从 std::cin
获取用户输入到 double
类型的变量中。这是在复数的上下文中,所以它经常碰巧有一个数字输入 5i
或 5.4565i
.
考虑 main()
函数中的以下代码:
while (true) {
double c;
std::cin >> c;
std::cout << c << "\n\n";
}
事情是这样的:
In: 0.45
Out: 0.45
// OK
In: 5 0.45
Out: 5
0.45
// OK
In: 0.45i
Expected out: 0.45
Acutal out: 0
0
0...
我猜这是因为它没有将 0.45i
识别为 double
。那么我如何正确地从 0.45i
中获取值 0.45
,忽略尾随的 i
?
尝试阅读 std::string
然后手动解析它。
先读取一个字符串,然后转换为double,
$ cat ans.cpp
#include <cstdlib>
#include <iostream>
int main()
{
std::string str;
double dbl;
while (std::cin >> str) {
dbl = std::strtod(str.data(), NULL);
std::cout << dbl << std::endl;
}
}
首先你将每个白色 space 分隔的字符串读入 str
。 strtod
函数会尝试获取尽可能多的字符组成浮点数,包括十六进制浮点数。它 returns 从字符串的这一部分解析的双精度值。第二个参数可以是一个 char *
指针,它指向一个传递的最后一个被解析的字符。如果您不想简单地丢弃尾随字符,这将很有用。如果为空则忽略。
一种方法是将输入作为字符串,然后使用 for 循环逐个字符地分析它。然后将其转换为 double 而忽略 i.You 可以将字符串分为三部分,即整数部分、小数部分和 i.
为了分隔它们,您可以使用 if(c[i]=='.') 和 if(c[i]=='i') 等条件。
您可以测试输入字符串的状态。如果输入 失败 ,只需在字符串中获取有问题的标记并继续。例如:
double d;
for(;;) {
std::string dummy;
std::cout << "Input :";
std::cin >> d;
if (std::cin.fail()) { // was input numeric?
std::cin.clear();
std::cin >> dummy;
if (dummy == "END") break; // out of the infinite loop...
std::cout << "Non numeric: >" << dummy << "<" << std::endl;
}
else {
std::cout << "Numeric: " << d << std::endl;
}
}
我需要从 std::cin
获取用户输入到 double
类型的变量中。这是在复数的上下文中,所以它经常碰巧有一个数字输入 5i
或 5.4565i
.
考虑 main()
函数中的以下代码:
while (true) {
double c;
std::cin >> c;
std::cout << c << "\n\n";
}
事情是这样的:
In: 0.45
Out: 0.45
// OK
In: 5 0.45
Out: 5
0.45
// OK
In: 0.45i
Expected out: 0.45
Acutal out: 0
0
0...
我猜这是因为它没有将 0.45i
识别为 double
。那么我如何正确地从 0.45i
中获取值 0.45
,忽略尾随的 i
?
尝试阅读 std::string
然后手动解析它。
先读取一个字符串,然后转换为double,
$ cat ans.cpp
#include <cstdlib>
#include <iostream>
int main()
{
std::string str;
double dbl;
while (std::cin >> str) {
dbl = std::strtod(str.data(), NULL);
std::cout << dbl << std::endl;
}
}
首先你将每个白色 space 分隔的字符串读入 str
。 strtod
函数会尝试获取尽可能多的字符组成浮点数,包括十六进制浮点数。它 returns 从字符串的这一部分解析的双精度值。第二个参数可以是一个 char *
指针,它指向一个传递的最后一个被解析的字符。如果您不想简单地丢弃尾随字符,这将很有用。如果为空则忽略。
一种方法是将输入作为字符串,然后使用 for 循环逐个字符地分析它。然后将其转换为 double 而忽略 i.You 可以将字符串分为三部分,即整数部分、小数部分和 i.
为了分隔它们,您可以使用 if(c[i]=='.') 和 if(c[i]=='i') 等条件。
您可以测试输入字符串的状态。如果输入 失败 ,只需在字符串中获取有问题的标记并继续。例如:
double d;
for(;;) {
std::string dummy;
std::cout << "Input :";
std::cin >> d;
if (std::cin.fail()) { // was input numeric?
std::cin.clear();
std::cin >> dummy;
if (dummy == "END") break; // out of the infinite loop...
std::cout << "Non numeric: >" << dummy << "<" << std::endl;
}
else {
std::cout << "Numeric: " << d << std::endl;
}
}