I got 2 arrays :
data[256] = "1@2@3@4@5"
question[256][256];
I need to split the number before the @ into an array..
for example :
question[0][] = 1
question[1][] = 2
question[2][] = 3
question[3][] = 4
question[4][] = 5
It doesnt metter if I have the @ in, or not.
This is what I wrote :
int i = 0, j = 0;
data = "1@2@3@4@5";
for (i = 0 ; i < strlen(data) ; i++)
{
for (j ; data[j] != '@' ; j++)
{
question[i][j] = data[j];
}
j++
}
printf ("%s\n", question);
The problem is, it works untill the first @, and then stops.
It only put the first @ into question, and then stops.
(basiclly I’m supposed to get the same output for printing both data, and question).
There are a few problems.
First,
printfonly prints the string until the first terminating zero character ('\0'), which happens after the first “part” inquestion(even though there are other parts. Instead, you will need to print all:Make sure you null-terminate (
'\0') the rows ofquestionbefore, so you don’t print garbage for uninitialized rows. or just maintain the index of the last-good row and iterate until thatAlso, the loop
will stop at the first
'@', and all consequent iterations of the outside loop will evaluate the samej(which is the index of'@', so the loop is skipped in further iterations. You will need to advancejafter the inner loopyou will also need to maintain a last-
jposition after the last'@'to be able to calculate the position ofjfrom the last'@', so you can index intoquestion[i]properly. setlastjto the value ofjafter is extra advancement suggested in the previous paragraph. Also, the second index ofquestionshould bej-lastjfrom now on.Yet another thing about the inner loop: as it is, it will advance past the string in
dataafter the last'@', so you will have to check for noll-termination as well.Also, make sure you null-terminate the strings in
question, otherwiseprintfwill produce garbage (and possibly seg-fault when reaching memory not allocated to your progam). just writeafter the inner loop. (
jwill have pointed after the last written index at the end of the inner loop)Yet one more thing: do not iterate
iuntil the length ofdataas you will not need to touch that many elements (and likely will overindexdatain the inner loop). Use awhileloop instead, incrementingionly until you have covereddatawithjin the inner loopNote: look up
strtokto make the tokenization easier on your part