-1

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?

Xantium
  • 11,201
  • 10
  • 62
  • 89
atg963
  • 197
  • 1
  • 3
  • 14

4 Answers4

4

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

kdhp
  • 2,096
  • 14
  • 15
  • Ok awesome this is working just one problem though when I type quit it doesn't exit the program any idea why? – atg963 Nov 06 '14 at 04:22
  • 2
    Because `fgets()` also writes the newline character. – Crowman Nov 06 '14 at 04:25
  • 1
    Actually just got it didn't realize that the fgets puts a \n at the end of the input string so just add \n to the end of the strcmp line and it works perfect! – atg963 Nov 06 '14 at 04:27
1

scanf() will return number of elements successfully read I will make use of it like below

#include<stdio.h>
#include<string.h>
int main()
{
   int a[20];
   int i=0;
   printf("Keep entering numbers and when you are done press some character\n");
   while((scanf("%d",&a[i])) == 1)
   {   
      printf("%d\n",a[i]);
      i++;
   }   

   printf("User has ended giving inputs\n");
   return 0;
}
Gopi
  • 19,784
  • 4
  • 24
  • 36
-1

You can use a do while loop:

do
{
    // prompts the user 
}
while (valueGiven != "quit");
kdhp
  • 2,096
  • 14
  • 15
Gabriel
  • 367
  • 2
  • 5
  • 15
-1
using do-while loop. 

   char *i = null;
   char ch = 'a';/
   do{
    scanf("%s", &i);

    /*do my program here*/
    myMethod(i);
    printf("Do you want to continues.. y/n");
    ch =  getchar();

    }while(ch != 'q');
Muhammad Danish
  • 111
  • 1
  • 6
  • 20