0
What's wrong with my logic? My code is not working
Write a program in C to split string by space.... But the code is not working. https://code.sololearn.com/c2a14a20a6a2/?ref=app
2 Respostas
+ 2
//C program to split a string
#include <stdio.h>
#include <string.h>
int main()
{
char s[100], word[100];
int i=0,j=0;
scanf(" %[^\n]", s);
while(s[j]!='\0'){
//strcpy(word[i], s[j]); //strcpy takes char pointer not chars
word[i]=s[j];
if(s[j]==' ' || s[j+1]=='\0'){
word[i+1]='\0'; //MARK THE END OF WORD SO OTHER CHARACTERS WON'T SHOW UP
printf("%s\n", word);
i=-1; //i++ below makes it zero
}
i++;
j++;
}
return 0;
}
+ 1
You also need to think about how to handle a sentence with multiple spaces. If your goal is to split it into words at space boundaries you could use strtok() in string.h to simplify it:
char s[100], *word;
fgets(s, sizeof(s), stdin);
for (word = strtok(s, " \n"); word; word = strtok(NULL, " \n"))
puts(word);