how to convert an array of characters to integer

I use ifstream to read a set of input from a file which consist of only numbers. I store these numbers in an char array. I need to use this numbers to do calculations. How can I convert dem to integer?
You can use atoi: http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
If you like C++ more than C, you can try with stringstreams: http://www.cplusplus.com/forum/articles/9645/
Bazzy -
can the ifstream object just be followed with >> to insert into existing variables i.e.:

int int1;
int int2;

ifstream ifs("somefile");
ifs >> int1 >> int2;

int int3 = int1 + int2;

I'm still weak with stream concepts...
closed account (L3ApX9L8)
Yep, stringstreams are the way to go...
here's an example i found somewhere...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <sstream>

int main()
{
  using namespace std;

  string s = "1234";
  stringstream ss(s); // Could of course also have done ss("1234") directly.
  
  int i;
  ss >> i;
  cout << i << endl;
  
  return 0;
}
Last edited on
The Boost Conversion Library (http://www.boost.org/doc/libs/1_38_0/libs/conversion/index.html) has lexical_cast.

1
2
3
string foo = "1234";
int bar = lexical_cast<int>(foo);
string baz = lexical_cast<string>(bar);


Sweet stuff.

1
2
3
4
5
6
try {
    string foo = "123v";
    int bar = lexical_cast<int>(foo);
} catch (bad_lexical_cast& ex) {
    cerr << ex.what() << endl;
}


This allows you to catch problems that atoi() and other methods silently ignore.

Topic archived. No new replies allowed.