How to extract input from a txt file and convert string to double?

Hi everyone,

I am an absolute beginner self learning C++ and would require some help for this problem I am facing please! Sorry I really do not have any idea the level of difficulty for this question so I thought since I'm a beginner so I shall post it here! Many thanks in advance. Cheers.

this is what I aim to achieve:
1) read the number from the first line of a single column text file
2) extract the number to perform calculation
3) write the new value to another text file
4) loop back to step 1 to read the second line of the column and keep looping for maybe say 5 times and exit

I have used the code from the http://www.cplusplus.com/doc/tutorial/files/

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h> //added this for converting string to double
#include <stdlib.h> //added this for converting string to double
#include <math.h> //added this for converting string to double

using namespace std;

int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl; // perform calculation here
}
myfile.close();
}

else cout << "Unable to open file";

return 0;
}

instead of printing the cout value, I would like it to perform some simple calculation say, value from txt file * 2. I was told that because the value from the text file is a string and I have to convert it into a double! which led me to the command "atof" and "strtod" which is where I am currently stucked at the moment. I've tried many ways, going through books and websites but it still wouldnt work.

Thank you very much and I deeply appreciate your help.

Jawsh

I would use a stringstream to convert to a double.
Don't use atoi or atod or whatever as they are non-standard functions.

If you want a good standard function make one using stringstreams.
1
2
3
4
5
6
7
8
9
#include <sstream>

template <typename T> T convert_to (const std::string &str)
{
  std::istringstream ss(str);
  T num;
  ss >> num;
  return num;
}


This will return a type you define from a string. So to convert from a double:

double d = convert_to <double> ("23.334");
Just use this call in the loop and preform your calculation with a double as you desired.
atoi lives in the cstdlib, making it pretty standard, although it's not so resilient as a stringstream.
atoi() is standard. It's itoa() that is non-standard.
Thank you everyone!

I have managed to achieve my desired outcome using stringstream.

Cheers.

Jawsh
Topic archived. No new replies allowed.