I'm trying to convert a string to an integer and store it in the same variable multiple time through a loop. For some reason it never works after the first time, it screws the number up.

#include <stdlib.h>
#include <string>
#include <iostream>
#include <cstdio>
#include <sstream>

using namespace std;

int main(int argc, char *arg[]){

string test("329034023");
long testNum = 0;
	for(int i =0; i < 2; i++){
		testNum = 0;
		testNum = atoi(test.c_str());
                cout<<"number "<<test<<" is: "<<testNum<<endl;
		test="23423423423";
	}
return 0;
}

any suggestions? I also tried using the istringstream but had the same results.

walom, your give the atoi function a overflow parameter. the max integer is 2147483647, which is less than "23423423423", so the result of atoi is incorrect.

I give you two advices:
1. use atol instead of atoi, which turns a string to a long integer
2. refer to the number_limits in STL, you can find the max integer there

Don't use such a adhoc method.
Use the STL method like this:

#include<sstream>
 inline std::string stringify(double x)
 {
   std::ostringstream o;
   if (!(o << x))
     cou<<"Bad Conversion";
   return o.str();
 } 

//Heres is how to use it:
string s1("123456");
int number=stringify(s1);
cout<<number;

For more, refer :http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.