-3

How can I rewrite my readDetails function without using stod() or strtod() in C++? The compiler I will be using doesn't have c++11 enabled and I get

'stod' was not declared in this scope error

int readDetails(SmallRestaurant sr[])
{
//Declaration
ifstream inf;

//Open file
inf.open("pop_density.txt");

//Check condition
if (!inf)
{
    //Display
    cout << "Input file is not found!" << endl;

    //Pause
    system("pause");

    //Exit on failure
    exit(EXIT_FAILURE);
}

//Declarations and initializations
string fLine;
int counter = 0;
int loc = -1;

//Read
getline(inf, fLine);

//Loop
while (inf)
{
    //File read
    loc = fLine.find('|');
    sr[counter].nameInFile = fLine.substr(0, loc);
    fLine = fLine.substr(loc + 1);
    loc = fLine.find('|');
    sr[counter].areaInFile = stod(fLine.substr(0, loc));  //line using stod
    fLine = fLine.substr(loc + 1);
    loc = fLine.find('|');
    sr[counter].popInFile = stoi(fLine.substr(0, loc));
    fLine = fLine.substr(loc + 1);
    sr[counter].densityInFile = stod(fLine);   //line using stod
    counter++;
    getline(inf, fLine);
}

//Return
return counter;
}

Below is the text I am trying to read:

Census Tract 201, Autauga County, Alabama|9.84473419420788|1808|183.651479494869 Census Tract 202, Autauga County, Alabama|3.34583234555866|2355|703.860730836106 Census Tract 203, Autauga County, Alabama|5.35750339330735|3057|570.60159846447

TMosley
  • 3
  • 2

1 Answers1

0

Use std::istringstream.

std::string number_as_text("123");
int value;
std::istringstream number_stream(number_as_text);
number_stream >> value;

Edit 2: For those pedantic people:
The example below reads a double. Very similar pattern to the above reading of an integer.

std::string number_as_text("3.14159");
double pi;
std::istringstream number_stream(number_as_text);
number_stream >> pi;

You could also use a variant of sprintf.

Edit 1: Another parsing method
You could try:

std::string tract;
std::string county;
std::string state;
double value1;
char separator;

//...
std::ifstream input("myfile.txt");
//...
std::getline(input, tract, ',');
std::getline(input, county, ',');
std::getline(input, state, '|');
input >> value1;
input >> separator;
//...
input.ignore(100000, '\n'); // Ignore any remaining characters on the line

The above doesn't require separate string to number conversion.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154