-2

The code is supposed to print out 13:Hello World!, but the output is only 13:.

#include <stdio.h>
   int main(){

  char *str = "Hello World!\n";

 int Laenge= 0;

  while (*str++){

   ++Laenge;
   }  
  printf(" %d:%c\n", Laenge, *str);
  return 0;
   }
n00n04
  • 3
  • 2
  • Insert the code as a text and not as an image, please – Marco Balo Nov 27 '22 at 18:07
  • Does this answer your question? [Why does C's printf format string have both %c and %s?](https://stackoverflow.com/questions/10846024/why-does-cs-printf-format-string-have-both-c-and-s) – Tarick Welling Nov 28 '22 at 08:58

4 Answers4

2

You set str to point to the beginning of the string, and then you increment str till you get to the end. By that time, str is now pointing to the end of your string.

Try using a different pointer to walk through your string, or just save a copy of the pointer for later use.

It also looks like you're syntax is wrong for the print statement. I haven't coded in C for decades. I'm a Python user now. But I think *str would reference one char, and you want to reference the entire string. So if str was not corrupted, use %s and str instead of %c and *str in your printf().

GaryMBloom
  • 5,350
  • 1
  • 24
  • 32
  • I changed the parameter as you suggested, however the output was 13:%d:%s. I don't really understand why this happened. – n00n04 Nov 27 '22 at 18:33
0

You can interate till you find the null character!

#include <stdio.h>

int main()
{
    char *str = "HELLO WORLD!\n";
    int len = 0;
    
    while(*(str + len) != '\0'){
        len++;
    }
    printf("%d:%s", len, str);

    return 0;
}

Your code is not working because your are incrementing the original string and converting it to '\0'. Use a walker.

0
  • you need to remeber the original str pointer

  • you should printf str not *str

    #include <stdio.h>
    int main(){
    
     char *str = "Hello World!\n";
     char *temp = str;
     int Laenge= 0;
    
     while (*temp++){
    
       ++Laenge;
     }  
     printf(" %d:%c\n", Laenge, str);
     return 0;
    

    }

pm100
  • 48,078
  • 23
  • 82
  • 145
0

The code is only supposed to do what it has been programmed to do, to the letter of the law. Unfortunately, what's written doesn't always coincide with what the programmer intended the program to do.

In the while loop, you increment str until you reach the end, at which point the while loop ends. Now the pointer points to the end of the string. Other than that, the format specifier for a string is %s, not %c. The %c would only print a single character. Change *str to str, unless you want to print a single character, but then you mentioned the expected output is supposed to be Hello, World.

Note: Do not post text as an image. Post text as text, one can't copy and paste your code from an image. It's difficult to see where the problem may be arising from, and hence is difficult to debug.

Harith
  • 4,663
  • 1
  • 5
  • 20