hi, i have a string like string s = "1234" and i want separately the integers 1 ,2 ,3 4 as integers , so how do i do it? i tried using atoi as follows :

char * ss[10];
ss = atoi(s.c_str());
int x = ss[0];

for getting 1 but it shows error
please help

Recommended Answers

All 7 Replies

I did it like this:

//separate each digit & place in array
   nums[0] = number/1000; //first digit
   nums[1] = (number%1000)/100; //second digit
   nums[2] = (number%100)/10; //third digit
   nums[3] = number%10; //fourth digit

Look at each characters in ss.
Use a loop so i increases for 0 to #characters ins ss
If ss is not an integer, go to the next character
If ss is an integer, subtract '0' from the character (this changes '2' into 2) and store it as required. Another array would be useful.

You are using atoi() wrong. It returns an integer.

char *str = "1";
int _one = atoi(str);

Look at each characters in ss.
Use a loop so i increases for 0 to #characters ins ss
If ss is not an integer, go to the next character
If ss is an integer, subtract '0' from the character (this changes '2' into 2) and store it as required. Another array would be useful.

i tried the following but am getting some garbage values for num:


#include <cstdio>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
	int i,l;
	string s ="1 1 2 3";
	l = s.length();
	const char *ss;
	ss = new char[s.size()+1];
	ss = s.c_str();
	int num[8];
	for(i=0;i<l;i++)
	{
		if(isdigit(ss[i]))
		num[i]=ss[i]-0;
	}
	for(i=0;i<l;i++)cout<<num[i];

	return 0;
}
int num[8];
	for(i=0;i<l;i++)
	{
		if(isdigit(ss[i]))
		num[i]=ss[i]-0; // I did not say subtract 0, did I?
	}                       //  What good does subtracting 0 do?
}

When you create num it's loaded with garbage. If you don't load a value into an element, garbage remains.

But why would you create a num value for all ss values? Didn't you say there are only 4 integers to convert? Use a different index for num instead of i.

you want to separate string "12345" to int 1 2 3 4 5 right?
try this

string numStr = "12345";  // this is ur input;
int num = atoi(numStr.c_str());
int seperatedNum;
while(num > 0)
{
          seperatedNum = num%10;
          // ptint or stroe seperatedNum whatevr u want
          seperatedNum = num/10;
}

hope this is what u want.

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.