Arfondol
Arfondol

Reputation: 3

C Ending a loop with user input

I'm trying to write a program that lets the user insert integer values into an array until they enter a specific key to stop, say ENTER, or X.

int array_numb[100];
char quit = 'x';
printf("Enter as many values into the array as you want, pressing x will end the loop\n");
while(1==1){
    int i = 0;
    scanf("%i",&array_numb[i]);
    i++;
    array_numb[i] = quit;
}

I know it's wrong but this is my thought process. Any ideas? thanks for the help

Upvotes: 0

Views: 3058

Answers (4)

Black
Black

Reputation: 21

You could learn something and use signals: http://man7.org/linux/man-pages/man7/signal.7.html

Register SIGINT, override it, let it check which key was pressed, then let it change a variable. In your loop check if this variable is 0 or 1.

Signals have top priority, signal code will be executed no matter the loop. Example: http://www.thegeekstuff.com/2012/03/catch-signals-sample-c-code/

It's overkill for this case but a fun thing to know. Signals are the way how an OS is managing events, like process kills, keyboard input etc. Be warned, how to use this is OS specific and has not much to do with C itself.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

  1. Enter as many values into the array as you want while having int array_numb[100];, at some point you will be in trouble. What if the user enters more than 100 numbers before entring the sentinel value? You'll be overruning the allocated memory, isn't it?

  2. You should check the return value of scanf() to ensure proper input. A mismatch in the supplied format specifier and the type of input will cause scanf() to fail. Check the man page for details.

  3. You need to have a break statement inside while(1) loop to break out. Otherwise, you need to have a conditional statement in the controlling expression for while() loop to terminate the loop.

Note: IMHO, the best way to stop scanning user input is to comapre the return value of scanf() against EOF, which can be produced by pressing CTRL+D on linux and CTRL+Z in windows.

You can check this answer for your reference.

Upvotes: 2

Spikatrix
Spikatrix

Reputation: 20252

scanf, with %i, will fail to scan a number when invalid data, such as a character is inserted and will return 0(in your case) if it fails.

Just check the return value of scanf. If it is zero, use

if(getchar()=='x') //or if(getchar()==quit)
  break;

Note: Clear/flush the standard input stream(stdin) using

int c;
while((c=getchar())!='\n' && c!=EOF);

after the loop as well as after the break; .

Upvotes: 0

Gopi
Gopi

Reputation: 19874

The same thing can be achieved as shown below: scanf() can fail and check the return value. When a character is scanned scanf() fails

int i=0;
printf("Enter as many values into the array as you want, pressing x will end the loop\n");
while(i<100 && scanf("%d",&array_numb[i])==1)
{
   i++;
}

Upvotes: 1

Related Questions