Converting String to Double

I am dealing with an input file with comma separated values. Each value is either an integer, a double or a string. There are six values per line with the first line being the labels for each value.

I am trying to find the maximum of the fourth value. I am able to take the input and single out the fourth value with the following code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
double findmax () {
  //Open the file for input                                                                                                             
  std::ifstream myfile;
  myfile.open ("file.csv");
  //check that the file is open                                                                                                         
  if (!myfile.is_open()){
     cout << "Unable to open file";
     exit (1);
  }
  std::string line;
  double max=0.0;
  string array[6];
  //read each line and convert to a string.                                                                                             
  while (myfile.good() ){
    int delim=0;
    int n=0;
    getline(myfile,line);
    delim=line.find_first_of(',');
    array[n]=line.substr(0,delim);
    cout << array[n] << endl;
    n++;
    while (n<6){
      array[n]=line.substr(delim+1,line.find_first_of(',',delim+1)-delim-1);
      delim=line.find_first_of(',',delim+1);
      cout << array[n] << endl;
      n++;
    }
  }
  myfile.close();
  return 0.02;
}


Just after line 27 I tried adding in the following code to check if the fourth element was great than the maximum.

1
2
3
if (atof(array[3])>max){
max=atof(array[3]);
}


When I try to compile I get the following error.

1
2
3
4
$g++ fibroblast.cpp
file.cpp: In function ‘double findmax()’:
file.cpp:28: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘double atof(const char*)’
file.cpp:29: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘double atof(const char*)’


where line 28 refers to the line for the if statement I added.

I am using the following as well

#include<string>

As you may be able to see from my code I am not very proficient with c++. Any help would be appreciated but please realize that my ability to grasp jargon is somewhat limited. Thanks so much.
atof() takes a const char*, not a string. This is exactly what the compiler is trying to say, as you are passing a std::string where the function wants a const char* and it can't convert the two. Use c_str() to get a const char*.
Topic archived. No new replies allowed.