NouName NouName - 25 days ago 11
C Question

Reading whole input instead of single line

I have written program which changes from lowercase letter to uppercase. Problem is, i dont know how to make it read whole text instead of one line. Program returns output after pressing enter and I want it to do so, after CTRL+Z.

#include <stdlib.h>
#include <stdio.h>


void makeUpper(char *s) {
int i;
for(i = 0; s[i] != '\0'; i++){
s[i] = toupper(s[i]);
}
printf("%s", s);
}


int main() {
char string[1000];

fgets(string, 1000, stdin);

makeUpper(string);
return 0;
}

usr usr
Answer

fgets() will stop once it encounters a newline. So, you can't workaround it to read multiple lines. So, you'll have to look at alternatives.

One way is is use getchar() is a loop and read as long as there's a room in the buffer or EOF is received.:

int main(void) {

    char string[1000];
    size_t i = 0;

    do {
        int ch = getchar();
        if (ch == EOF) break;
        string[i] = ch;
        i++;
    } while (i < sizeof string - 1);
    string[i] = 0;

    makeUpper(string);
    return 0;
}

Remember, ctrl+Z works on Windows (to send EOF). On *nix-like systems, you'll have to use Ctrl+D to send EOF.

Comments