I want to extract a floating point number from a CString formatted as: (example extract 22.760348)
Incidence_angle(inc)[deg] :22.760348
Basically I am reading a plain text file containing some parameters, and I want to perform some calculations on the values. I read the file using a CStdioFile object and extracting each line using the readString method as follows:
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);
}
}
I tried using scanf because I couldnt think of any other way.
I apologize if this question seems very basic and stupid, but I have been stuck on it for a long time and would apppriciate some help.
edit: took out the proof of concept program I wrote, caused confusion
_tscanf()
returns the number of assignments made, not the value read:
theeta_i = _tscanf(L"Incidence_angle(inc)[deg] :%f",&theeta_i);
so theeta_i
will contain 1
( .0
) if a float
was successfully read. Change to:
if (1 == _tscanf(L"Incidence_angle(inc)[deg] :%f",&theeta_i))
{
/* One float value successfully read. */
}
That should be _stscanf()
to read from a buffer, _tscanf()
will be waiting for input from standard input.
Assuming that tmp
is CString
, the correct code is
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
}
}
Why not use atof ?
Example taken from the link:
/* 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 %f\n" , n, m );
return 0;
}
Why not do it the C++ way altogether?
This is just a hint:
#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;
}
If you want to use as you have illustrated, using cstring only, try strtod()
also. Source: man -s 3 strtod
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.