从 CString 中提取浮点数

Extract a floating point number from a CString

本文关键字:浮点数 提取 CString      更新时间:2023-10-16

我想从格式化为:(示例提取 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,因为我想不出任何其他方法。

如果这个问题看起来非常基本和愚蠢,我深表歉意,但我已经坚持了很长时间,并希望得到一些帮助。

编辑:拿出我写的概念验证程序,引起混乱

假设tmpCString,正确的代码是

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()将等待来自标准输入的输入。