-1

I have a bit of code that is supposed to get numbers from input until EOF and put them inside an array.

#include <stdio.h>

int main(){
  int numbers[250000],i,m=0;
  while(scanf("%d",&i)!=EOF){
    numbers[m]=i;
    m++;
  }
}

My problem is that I need to check if the input is valid (if it is a number). If it is not a number I need to print out a message that says something along the lines "Wrong input" and end the program.

Can somebody please help me?


PS. I know that this question has been asked several time, I have googled, but I have not been able to figure out from the answers how to adapt the code to my situation. So, sorry if the question seems redundant.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Jano
  • 35
  • 1
  • 7

3 Answers3

0

scanf's return value is an integer, telling you how many items were succesfully read. If your single integer was read successfully, scanf will return 1.

#include <stdio.h>

int main(){
  int numbers[250000],i,m=0;
  int itemsRead = 0;
  while(itemsRead = scanf("%d",&i) != EOF){
     if (itemsRead != 1)
     {
        printf("Wrong input");
        return 0;
     } 
     numbers[m]=i;
     m++;
  }
}
josemartindev
  • 1,413
  • 9
  • 17
0

You need to read the input as a string, validate that its context is actually a number, and then assign it to the array's cell, like this:

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

#define MAXINPUT 100

int main() {
  int numbers[250000],m=0;
  char input[MAXINPUT] = "";
  while(scanf ("%s", input)!=EOF) {
    for (size_t i = 0; i < strlen(input); i++)
        if (!isdigit(input[i]))
        {
            printf ("Entered input is not a number\n");
            exit(1);
        }
    // here we know that 'input' is a number
    numbers[m] = atoi (input);
    m++;
  }
  return 0;
}

PS: I would use fgets() instead of scanf().

gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

Shortening @gssamaras code, you can have something simpler, like this

#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
    int main()
     {
      int numbers[250000],i,m=0;
      char temp;
      while(scanf("%c",&temp)!=EOF)
      {
         if(!isdigit(temp)))
           {
             printf("Wrong input");
              break;
           }
        numbers[m]=atoi(temp);
        m++;
      }
    }
Aravind Balaji
  • 57
  • 2
  • 10