string to int

I am trying to convert a string to a signed int from a file:
-1
2
3
4
5
6
7
8
9
Trying to use atoi with no luck.
val = atoi(line); did not work .
Any ideas?

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h> /* atoi */
using namespace std;

int main () {
string line;
int val;
line = "-10";
val = atoi(line);
ifstream myfile ("int9.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';

}
myfile.close();
}

else cout << "Unable to open file";
return 0;
}
atoi() expects a C-style string, so you need to pass it one of those instead of an std::string. You can get one using the c_str() method of std::string, though, so just add that in and it should work.
Yikes.
Is this what I can do?
http://www.cplusplus.com/reference/string/string/c_str/

I thought parsing a string to an int would be simple. I might look for another approach.
Any other ideas?
Java is my native language.
Thanks
Why from string?

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
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

void read( istream & in ) {
  int sum = 0;
  int value;
  while ( in >> value ) {
    sum += value;
    std::cout << value << '\n';
  }
  std::cout << "total " << sum << "\n\n";
}

int main( int argc, char * argv[] ) {
  if ( 1 < argc ) {
    std::ifstream fin( argv[1] );
    read( fin );
  } else {
    read( std::cin );
  }

  std::string word = "42 7";
  std::istringstream foo( word );
  read( foo );

  return 0;
}
Why from a string.?
I want to read a line from a file and convert to an integer form some matrix math.
My code reads one integer at a time, but since your file has only one integer per line, the code effectively reads one line at a time. Formatted stream input.
Topic archived. No new replies allowed.