从 CString 中提取浮点数
Extract a floating point number from a CString
我想从格式化为:(示例提取 22.760348)
Incidence_angle(inc)[deg] :22.760348
基本上,我正在读取一个包含一些参数的纯文本文件,我想对这些值执行一些计算。我使用 CStdioFile 对象读取文件,并使用 readString 方法提取每一行,如下所示:
CStdioFile result(global::resultFile,CFile::modeRead);
while( result.ReadString(tmp) )
{
if(tmp.Find(L"Incidence_angle(inc)[deg]") != -1)
{
//extract value of theeta i here
// this is probably wrong
theeta_i = _tscanf(L"Incidence_angle(inc)[deg] :%f",&theeta_i);
}
}
我尝试使用 scanf,因为我想不出任何其他方法。
如果这个问题看起来非常基本和愚蠢,我深表歉意,但我已经坚持了很长时间,并希望得到一些帮助。
编辑:拿出我写的概念验证程序,引起混乱
假设tmp
是CString
,正确的代码是
CStdioFile result(global::resultFile,CFile::modeRead);
while( result.ReadString(tmp) )
{
if (swscanf_s(tmp, L"Incidence_angle(inc)[deg] :%f", &theeta_i) == 1)
{
// Use the float falue
}
}
为什么不使用 atof?
从链接中获取的示例:
/* atof example: sine calculator */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main ()
{
double n,m;
double pi=3.1415926535;
char szInput [256];
printf ( "Enter degrees: " );
gets ( szInput );
n = atof ( szInput );
m = sin (n*pi/180);
printf ( "The sine of %f degrees is %fn" , n, m );
return 0;
}
为什么不完全以C++的方式进行呢?
这只是一个提示:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
double double_val=0.0;
std::string dump("");
std::string oneline("str 123.45 67.89 34.567"); //here I created a string containing floating point numbers
std::istringstream iss(oneline);
iss>>dump;//Discard the string stuff before the floating point numbers
while ( iss >> double_val )
{
std::cout << "floating point number is = " << double_val << std::endl;
}
return 0;
}
如果您想按照所示使用,仅使用 cstring,也请尝试strtod()
。源: man -s 3 strtod
_tscanf()
返回所做的赋值数,而不是读取的值:
theeta_i = _tscanf(L"Incidence_angle(inc)[deg] :%f",&theeta_i);
因此theeta_i
如果成功读取float
,它将包含1
(.0
)。更改为:
if (1 == _tscanf(L"Incidence_angle(inc)[deg] :%f",&theeta_i))
{
/* One float value successfully read. */
}
这应该_stscanf()
从缓冲区读取,_tscanf()
将等待来自标准输入的输入。
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 使用提升将数据从 PyObject 复制到浮点数 *
- 使用浮点数和双精度数的非常小数字的数学
- 使用英特尔内联函数将打包的 8 位整数乘以浮点数向量
- 如何在 c++ 中将小数点后两位数的浮点数分配给另一个浮点数
- 返回浮点数的小数位数
- 找到一种使用 C++ 中的条件提取浮点数的方法
- 如何使用 sscanf 提取浮点数?
- 如何在 c++ 中使用 FFT 从 32 位浮点数组中提取频率
- Z3 SMT求解器 - 如何在FPA中提取浮点数的值
- 从C 中的字符串中提取浮点数的最简单方法
- 如何从字符串中提取浮点数
- 从 CString 中提取浮点数
- 如何从C++文件中的特定行中提取数字(浮点数)
- std::istream 提取运算符(双精度或浮点数)在 VS 2012 中非常慢
- 从浮点数中提取数字
- 精确地提取浮点数的小数部分
- 对某些标准流类插入和提取浮点数是否保留其值