Translate string into int type.

Hi Guys,
I want translate a number string into int type. such as "21354" to (int)21354. but the output is not correct. I can not find bugs. Please help me. Thanks.

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
#include <iostream>

using namespace std;


int main(){
	char tm[20] = "2135";
		
	const char tran = '0';
	
	int tmp=0;
	
	for(int tm_i=0;tm_i<20;tm_i++){
		if(tm[tm_i]=='\0')tmp=tm_i;
	}
		
	
	int intnum = 0;
	for(int i=tmp, int j=1,int flag=0;i>=0;i--){
		if(flag == 1){
			intnum += (int)(tm[i] - tran)*j;
			j*=10;
		}
		if(tm[i]=='\0')flag=1;
	}
	
	cout<<"string is:"<<tm<<endl;
	cout<<"int number is:"<<intnum<<endl;
	
	
	return 0;
}



string is:2135
int number is:-995611984
The atoi() method does this for you.

1
2
#include <cstdlib>
int atoi(const char *str);


http://cplusplus.com/articles/numb_to_text/

1
2
3
4
5
6
7
8
9
10
11
12
int str2int (const string &str) {
  stringstream ss(str);
  int n;
  ss >> n;
  return n;
}

string int2str (int n) {
  stringstream ss;
  ss << n;
  return ss.str();
}
nice.. but i hope you know its non-standard..
What do you mean it is non-standard?

It is in the C Standard Library. It is standard according to SVr4, POSIX.1-2001, 4.3BSD, C99, C89 and POSIX.1-1996. http://linux.die.net/man/3/atoi


It is not, however, C++. If you plan to use C++, then use C++ and avoid old stuff like atoi(). blackcoder41 has done you a double service already by both posting nice, drop-in code you can use and linking to a very well-written article which exactly answers your topic question.
sorry, i mean it's not ANSI C
YES IT IS.

I already wrote:
It is standard according to ... C89 [AKA ANSI C] ... http://linux.die.net/man/3/atoi

Maybe you are thinking of itoa(), which is common (but non-standard)?
oh yes it's itoa(), my mistake. just forget it.. thanks for correcting me anyway..

i'll just have your word.
which is common (but non-standard)
I only know because when I first began coding I used atoi() and itoa(), and was both surprised and peeved that the latter was so, well, non-portable (making code I wrote at home not work at school). Then I learned about such things as standards...
Topic archived. No new replies allowed.