Home > Blockchain >  Why is it not printing the string?
Why is it not printing the string?

Time:03-25

I'm trying to use getchar() to read each character from the standard input and arrange it through out the array, and finally printing it. The thing is, it isn't printing the array.

I've tried to use a for loop to print out the individual characters from the array, but still doesn't work. Any ideas?

Considering the string doesn't exceed the maximum of the array (30).

#include <stdio.h>

int main()  
{
int i, c;
char s[30];

    while((c=getchar()) != EOF){
        s[i] = c;
        i  ;
    }
    
    printf("%s", s);
    return 0;
}

Thank you for your help.

For those reading this with the same problem, I solved it by:

  • initializing i with 0;
  • initializing s with 0 values;
  • instead of EOF, I used '\n'.

CodePudding user response:

You got unlucky and your code didn't instantly crash. Instead you're overwriting memory at random.

The thing you're missing is initializing i with 0. Your code doesn't initialize it and it has whatever is in memory at that location.

Considering the string doesn't exceed the maximum of the array (30).

You better mean 29, or you're overwriting memory again. Your string has to end with a '\0' character. Speaking of, you should initialize s with 0 values as well, or you'll be printing garbage past the end of your string.

CodePudding user response:

#include <stdio.h>

#define STR_LEN 30
int main() {
    char str[STR_LEN   1]; // extra space for '\0' c-string delimiter
    int ci = 0; // character index begins at 0 in c-strings
    int ich;    // getchar() returns int that cover EOF
    //you may have to press Ctrl D in console to input EOF
    //OR more than STR_LEN chars in a single line   ENTER
    while ((ich = getchar()) != EOF && ci < STR_LEN) { // also not reading more than 30 chars
        str[ci] = ich;
          ci;
    }
    str[ci] = '\0';  // ending c-string with string delimiter at the end
    printf ("\nRead String: [%s]\n", str);
    return 0;
}
  • Related