1

I am new to the programming world and I'm trying to make a string split by using a loop that should split all characters separately but it's being ignored and basically ends with showing the input of the user instead of using the loop to separate the individual letters/characters. Have I missed declaring something important in the loop?

1
  • 1
    People are more likely to find this question if you tag the language
    – camille
    Commented Dec 16, 2018 at 18:40

3 Answers 3

2

for (i = 0; str[i] != '\0'; i++); <- there's a semicolon here, so your loop literally does nothing

also note that str[i] != '\0' is a very dangerous way of iterating your string. If your string doesn't contain a zero-terminal character, C will happily continue reading memory beyond the end.

3
  • strlen(str) will loop over str until it finds a null terminator. So there's really no difference between that and doing it manually. Unless you have i < strlen(str) as the loop condition in which case you've just made your loop O(n*n) instead of O(n)
    – Kevin
    Commented Dec 16, 2018 at 21:34
  • I guess you're correct on that one. You could always go with sizeof(str), but that will include \0. Long story short, C and strings are still not friends.
    – nitowa
    Commented Dec 16, 2018 at 21:39
  • It depends on what you want. sizeof(str) returns the number of bytes that str takes up, which in this case is 50. strlen(str) is the length of the C-style string str. Since fgets was used str will be a C-style string, i.e. it will have a null terminator. Just call strlen(str) once outside of the loop to be more efficient.
    – Kevin
    Commented Dec 16, 2018 at 21:42
0

There are few syntactical errors with what you posted.

 /* This should be <stdio.h>
 ... 
 /* Don't need a. semi-colon here
 int main();
 ...
 /* Calling getchar() will cause you to lose the first character of the
    the input
 */ 
    getchar();
    ... 
 /* Don't need a semi-colon here */
    for (i = 0; str[i] != '\0'; i++
    ...
    system("pause");
 }

With those adjustments you should find the code works.

Write text:
Hello world
Input: Hello world

H
e
l
l
o

w
o
r
l
d


sh: pause: command not found

I'm not on windows, so if the code on your end does not seem to work after making adjustments it is probably windows specific.

0

If you're using java, you can just split with an empty string and then loop through the list that's created from the split method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.