How do I convert from a string to a double, without using a c++ 11 compiler?

0 Bob huginstien · March 14, 2015
I need to convert this string to a double in my code, ( the stod part in the code.) how would I do this without using a  c++11 compiler? 

#include<iostream>
#include<cmath>
#include<fstream>
#include<iomanip>
#include <string>

using namespace std;

int main()
{
ifstream infile("input.txt"); //grabs file using filename
if (!infile.is_open()) //checks if the file is open
{
cout << "unable to open file..so exiting from program " << endl;
return 0;
}
int final_score, position, lineSize; //declares variables to be used
double score, total, final_s; //declares doubles to be used
string readLine, scoreAsString, totalAsString; //uses one string to read a line, one to get the score and one for the total
char readCharacter; //declares a temporary character to check the next byte
while (infile.peek() != EOF) //goes through all lines in the file
{
infile >> readLine; //puts a single line into readLine
lineSize = readLine.size(); //calculates the linesize
scoreAsString = ""; //resets the string to nothing
totalAsString = ""; //resets the string to nothing
for (position = 0; position<lineSize; position++)
{
readCharacter = readLine[position];
if (readCharacter == ' ') //searches for the space to find the end of the number
break;
scoreAsString += readCharacter;
}
for (position++; position<lineSize; position++)
{
readCharacter = readLine[position];
if (readCharacter == '\n' || readCharacter == '\r') //searches for newline
break;
totalAsString += readCharacter;
}

score = stod(scoreAsString, NULL); //converts string to double
total = stod(totalAsString, NULL);//converts string to double
final_s = (score * 100) / total;
final_score = static_cast<int> (ceil(final_s));
cout << "Final Score is " << fixed << setprecision(5) << final_s << endl;
if (final_score >= 90)
cout << "Excellent" << endl;
else if (final_score >= 80)
cout << "Well Done" << endl;
else if (final_score >= 70)
cout << "Good" << endl;
else if (final_score >= 60)
cout << "Needs Improvement" << endl;
else if (final_score <60)
cout << "Fail" << endl;
}
infile.close();
return 0;
}



Post a Reply

Replies

Oldest  Newest  Rating
0 Bob huginstien · March 14, 2015
I should have added we never learned stringstream, so it might get suspicious. 
0 Bob huginstien · March 14, 2015
Thank you, will  this work on a GNU GCC compiler ? 
0 Sadra Keshavarz · March 14, 2015
Yeah*
  • 1

C++

107,303 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator