Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Covert string to an array

Status
Not open for further replies.

OOzy

Programmer
Jul 24, 2000
135
SA
Hello

How can I convert this string to an array

a=1,3,4

such as

b[0]=1
b[1]=3
b[2]=4
 
You can use strtok() to extract the numbers from the string.


char p[] = "1, 3, -6, 0, 129";
int a[5], index = 0;

char * token = strtok(p, ",");

while(token) {
a[index++] = atoi(token);
token = strtok(0, ",");
}
 

you could also do this a different way as well

int getNextInt(char* array)
{
int return_value = atoi(array);
array = strstr(array,",")+1;
return return_value;
}

int main()
{
...
char* array = a;


while(array)
{
b[index++]=getNextInt(array);
}

}

I suggest this because i have had problems with strtok in the past. strstr has always treated me well :)

Matt
 
#inlcude<strstream>
using namespace std;
int main()
{
strstream x;
char* z;
int y=0;
x<<y;
z=x.str();
x>>y;
return 0;
} John Fill
1c.bmp


ivfmd@mail.md
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top