#163374 - NovaYoshi - Tue Sep 30, 2008 11:29 pm
I'm trying to write some code to let me split a string into sections, each section going into a new string, using a space to separate each. I'm trying to get this right so I can add argument support to my IRC bot's commands...
[edit] I asked on #C of Rizon, and Shahid helped me. He found what was wrong... and gave me the fixed source:
Code: |
#include <stdio.h> int main() { system("cls"); //clear the screen char buffer[1024]; char output[128][4]={"","","",""}; //where the split up text will go int x=0; int y=0; int z=0; char c=' '; fgets(buffer, 1024, stdin); //so spaces are read while(c!='\0')//until we go and find a null byte in the input string { puts("------------------------------"); c=buffer[x]; printf("(C:\'%c\' X:%d Y:%d Z:%d)", c,x,y,z); if(c==' ') //go and start filling the next buffer if we encounter a space { puts("Space encountered..."); output[z][y+1]='\0'; //finish the string with a null byte y=0; //We want to start filling from the beginning of the next buffer z++; //We want to start filling the next buffer } else if(isalpha(c)) //so returns and crap are caught { output[z][y]=c; //put the character in } else { puts("Was not alphanumeric... ignoring..."); } x++; y++; putchar('\n'); printf("Out1: %s\n",output[0]); printf("Out2: %s\n",output[1]); printf("Out3: %s\n",output[2]); printf("Out4: %s\n",output[3]); putchar('\n'); } output[z][y+1]='\0'; //add a null byte to that last buffer //Show the final results printf("Buffer: %s\n",buffer); printf("Out1: %s\n",output[0]); printf("Out2: %s\n",output[1]); printf("Out3: %s\n",output[2]); printf("Out4: %s\n",output[3]); return(1); } |
[edit] I asked on #C of Rizon, and Shahid helped me. He found what was wrong... and gave me the fixed source:
Code: |
#include <ctype.h> #include <stdio.h> int main() { system("cls"); char buffer[1024]; char output[4][128] = {'\0' }; //where the split up text will go int x=0; int y=0; int word=0; char c=' '; fgets(buffer, 1024, stdin); while(c != '\0')//until we go and find a null byte in the input string { c=buffer[x]; if(c==' ') //go and start filling the next buffer if we encounter a space { puts("Space encountered..."); output[word][y+1]='\0'; //finish the string with a null byte y=0; //We want to start filling from the beginning of the next buffer word++; //We want to start filling the next buffer } else { if(isalpha(c)) //so returns and crap are caught { output[word][y]=c; //put the character in } else { puts("Was not alphanumeric... ignoring..."); } y++; } x++; } output[word][y+1]='\0'; //add a null byte to that last buffer printf("Buffer: %s\n",buffer); printf("Out1: %s\n",output[0]); printf("Out2: %s\n",output[1]); printf("Out3: %s\n",output[2]); printf("Out4: %s\n",output[3]); return 0; } |