Search code examples
cinputterminaluser-input

Taking continuous input from user in C


I am working on a project where I have to take input from a user in the terminal in c until they input quit then I end the program. I realized I cant do this:

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

int main(int argc, char **argv){
    char *i;
    while(1){
        scanf("%s", i);

        /*do my program here*/
        myMethod(i);

    }

}

So my question is how can I go about taking this coninuous user input? Can I do it with loops or what else can I do?


Solution

  • First you have to allocate space for the string you are reading, this is normally done with a char array with the size of a macro. char i[BUFFER_SIZE] Then you read data into your buffer,fgets might be better than scanf for that. Finally you check your exit case, a strcmp with "quit".

    #include <stdio.h>
    #include <string.h>
    
    #define BUFFER_SIZE BUFSIZ /* or some other number */
    
    int main(int argc, const char **argv) {
        char i[BUFFER_SIZE];
        fgets(i, BUFSIZ, stdin);
        while (strcmp(i, "quit\n") != 0) {
            myMethod(i);
            fgets(i, BUFSIZ, stdin);
        }
    }
    

    Strings obtained with fgets are gurenteed null terminated