Your program is having undefined behavior here
printf("%s",str[i]);
because str[i]
is of type char
and you are printing it using %s
format specifier which is used to printf null terminated array of characters.
From C Standard#7.21.6.1p9
If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. [emphasis mine]
Also, avoid using scanf()
for string input. If not used carefully, it can have the buffer overflow problem. You should use fgets
instead.
Coming to your question:
The question is to find spaces between the string. And if spaces are detected the next word should be printed in the next line.
As I have suggested in comment, you can use strtok()
to do this by giving space as delimiter. The strtok()
will split the input string into tokens. A point to note about strtok()
is that it modifies the input string by being broken into smaller strings (tokens). If you are okay with it then you can do:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUF_SZ 20
int main() {
char str[BUF_SZ];
char *pch;
if (fgets (str, BUF_SZ, stdin) == NULL) {
perror ("fgets failed");
exit (EXIT_FAILURE);
}
str[strcspn (str, "\n")] = 0;
pch = strtok (str," ");
while (pch != NULL) {
printf ("%s\n", pch);
pch = strtok (NULL, " ");
}
return EXIT_SUCCESS;
}
After while
loop, the content of str
is not same as it was before calling strtok()
on it. Though, whether to modify the original input string or not doesn't make sense over here because after breaking it into tokens it is not more used.
Your question says - if spaces are detected the next word should be printed in the next line..
. If it is just about printing the words in new line, you can do:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_SZ 20
int main() {
char str[BUF_SZ];
int word_size = 0;
int i = 0, start = 0;
if (fgets (str, BUF_SZ, stdin) == NULL) {
perror ("fgets failed");
exit (EXIT_FAILURE);
}
str[strcspn(str, "\n")] = 0;
for (i = 0; str[i] != '\0'; i++) {
start = i;
if (str[i] != ' ') {
word_size++;
if (str[i+1] != '\0')
continue;
start++;
}
if (word_size != 0) {
printf ("%.*s\n", word_size, str + start - word_size);
word_size = 0;
}
}
return EXIT_SUCCESS;
}
This solution does not modify the input string but just parse it and if the space is detected next word printed in new line.