#My loop stops when there is a space in string

10 messages · Page 1 of 1 (latest)

fiery pivot
#

Question is how do i stop this

void name_reverse(char s[]){
  int len = 0;
  while (s[len] != '\0') {
    len++;
  }

  len--;

  while (len >= 0) {
    printf("%c", s[len]);
    len--;
  }

  
}

Basically, this takes the input string and reverses it and prints it. However, my first loop stops reading the string when there is a space
Example:

Hey
yeH

but

He y
eH

how to fix

wary pendantBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

fiery pivot
#

also I realise there is probably an easier way to do this lol

#

meant to use array notation asw

#

and no functions from string.h

spice ginkgo
#

this is more likely due to the way you read input

quaint lance
#

@fiery pivot I assume you use scanf("%s", buffer) to read your data.
scanf sucks, and the format specifiers aren't the same as the ones for printf.
For scanf the %s means to read a string, until a whitespace of any kind occurs (i.e. a space, a tab, a newline, etc).

If you want to reliably read entire lines you'll need to use fgets, smth like this:

char buf[1024];

fgets(buf, sizeof buf, stdin);
fiery pivot
#

okok tyyyy it works

#

!solved

wary pendantBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity