1

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;
}
NouName
  • 87
  • 5

2 Answers2

3

just put your fgets(string, 1000, stdin) into a while loop.here is the solution

#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];

    while(fgets(string, 1000, stdin)!=NULL)//for getting input untill pressing CTRL+Z.
    {
        makeUpper(string);
    }


    return 0;
}
Real73
  • 480
  • 4
  • 12
2

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.

P.P
  • 106,931
  • 18
  • 154
  • 210
  • "*`fgets()` will stop once it encounters a newline.*" It might be worth mentioning that this is Windows specific. On IX'ish systems `Ctrl-D` to indicate `EOF` very well ends `fgets()`. – alk Nov 08 '16 at 09:53
  • I wasn't referring to the `D``Z`difference, but to the fact that `Ctrl-Z` on windows would not end `fgets()` if already some input was given, whereas it would on UNIX (for `Ctrl-D` in this case). – alk Nov 08 '16 at 09:59
  • Sending EOF by whatever OS-specific means will end fgets(). But AFAICT, OP's problem is *not* detecting EOF but to read multiple lines (basically OP is handicapped by the fact that `fgets()` stops at a newline whereas he wants to read more until EOF is sent explicitly by him). – P.P Nov 08 '16 at 10:07