区分数字和其他符号 [c++]
Distinguishing between numbers and other symbols [c++]
我正在读取一个文本文件,并通过解析(逐行)提取其中的信息片段。下面是文本文件的示例:
0 1.1 9 -4
a #!b .c. f/
a4 5.2s sa4.4 -2lp
到目前为止,我能够使用空格' '
分隔符来拆分每行。因此,例如,我可以将"1.1"
的值保存到字符串变量中。
我想做的(这就是我卡住的地方)是确定我正在阅读的信息是否代表一个数字。使用前面的示例,这些字符串不表示数字:a #!b .c. f/ a4 5.2s sa4.4 -2lp
或者,这些字符串确实表示数字:0 1.1 9 -4
然后我想将表示数字的字符串存储到双精度类型变量中(我知道如何转换为双精度部分)。
那么,如何区分数字和其他符号呢?我正在使用c ++。
你可以这样做:
// check for integer
std::string s = "42";
int i;
if(!s.empty() && (std::istringstream(s) >> i).eof())
{
// number is an integer
std::cout << "i = " << i << 'n';
}
// check for real
s = "4.2";
double d;
if(!s.empty() && (std::istringstream(s) >> d).eof())
{
// number is real (floating point)
std::cout << "d = " << d << 'n';
}
eof()
检查确保数字后没有非数字字符。
假设当前(C++11)编译器,处理此问题的最简单方法可能是使用std::stod
进行转换。您可以为此传递一个size_t的地址,该地址指示在转换为双精度时无法使用的第一个字符的位置。如果整个输入转换为双精度,它将是字符串的末尾。如果是任何其他值,则至少部分输入未转换。
size_t pos;
double value = std::stod(input, &pos);
if (pos == input.length())
// the input was numeric
else
// at least part of the input couldn't be converted.
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 将无符号char*转换为std::istream*C++
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- vscode g++链路故障:体系结构x86_64的未定义符号
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 使用gcc从静态链接的文件中查找可选符号
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- VC++本机单元测试,找不到调试符号
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- 检查TCHAR数组输入是否为带符号整数C++
- 用符号版本替换对函数的所有调用
- 未解析的外部符号_MsiLocateComponentW@12.
- 如何打印boost多精度128位无符号整数
- C++模板函数,用于比较任何无符号整数和有符号整数
- 在 Mac 上使用 CMAKE 将 FFTW 和 FFTWPP 链接到项目中时未定义的符号