Search code examples
cloopsinputio

how to take input till "only" newline character or a space is inputted ?Basically how to run loop till you enter nothing as input?


i am trying to create a looping which keeps looping till "only" newline charater is inputted or maybe just a space (until nothing is entered to the input line).

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

    int main()
    {
        int num;
        while(1)
        {
            scanf("%d",&num);
            if(num==NULL)
                break;
        printf("%d",num);
        }
        return 0;
    }

Solution

  • You can't do that with scanf (at least not easily). If you want to process user input, scanf is a bad choice (in fact, in all my years of developing in C, I've never used scanf; I recommend you avoid it altogether).

    num==NULL makes no sense: num is a number, but NULL is a pointer value. If you want to check whether scanf was successful, you need to check its return value.

    I'd do something like:

    char line[100];
    while (fgets(line, sizeof line, stdin)) {  // read input line by line
        int num;
        if (sscanf(line, "%d", &num) != 1) {  // the line didn't start with a valid integer
            break;
        }
        printf("%d\n", num);
    }
    

    If you want to check specifically for an empty string, not just something that doesn't look like a number, you could use strspn:

    if (line[strspn(line, " \t\n")] == '\0') {
        // line contains spaces / tabs / newlines only