9

I have written an app in C which expects two lines at input. First input tells how big an array of int will be and the second input contains values separated by space. For example, the following input

5
1 2 3 4 99

should create an array containing {1,2,3,4,99}

What is the fastest way to do so? My problem is to read multiple numbers without looping through the whole string checking if it's space or a number?

Thanks.

Deepu
  • 7,592
  • 4
  • 25
  • 47
migajek
  • 8,524
  • 15
  • 77
  • 116

5 Answers5

22
int i, size;
int *v;
scanf("%d", &size);
v = malloc(size * sizeof(int));
for(i=0; i < size; i++)
    scanf("%d", &v[i]);

Remember to free(v) after you are done!

Also, if for some reason you already have the numbers in a string, you can use sscanf()

Denilson Sá Maia
  • 47,466
  • 33
  • 109
  • 111
  • I thought it'll look for numbers separated by "\n"? – migajek Mar 29 '10 at 17:24
  • 2
    `%d` (as well as most % conversions, but not all of them) automatically skips any whitespace. Read the scanf documentation for details! – Denilson Sá Maia Mar 29 '10 at 17:27
  • 2
    "If for some reason"? You should never use `scanf` and should prefer using `fgets` with `sscanf`. http://c-faq.com/stdio/scanfprobs.html – jamesdlin Mar 29 '10 at 19:16
  • @jamesdlin, sorry, but I disagree. If you really *know* how to use scanf, you can use it safely. And by knowing I mean really understanding all options and conversions from scanf. (read the entire manpage) – Denilson Sá Maia Mar 30 '10 at 19:55
  • 1
    The fact that it can leave unprocessed input in the input buffer should make you cringe. Yes, there are ways you can use `scanf` safely, but all the hoops you have to jump through simply don't make it worthwhile. `fgets` with `sscanf` is much simpler and has fewer gotchas for the uninitiated. – jamesdlin Mar 30 '10 at 21:22
  • I agree. If the input is string in nature, `fgets` is the best option. – Pankaj Dwivedi Mar 15 '15 at 11:37
  • `scanf("%d"...` does not enforce anything about a _line_ of input per OP's title. Should user input not be precisely formated as expected, this approach fails in many ways with it lack of error detection. OK for learners, but insufficient for good programming. – chux - Reinstate Monica Jan 31 '18 at 00:01
4

Here 'N' is the number of array elements of Array 'A'

int N, A[N];
printf("Input no of element in array A: ");
scanf("%d", &N);
printf( "You entered: %d\n", N);
printf("Input array A elements in one line: ");
for(int i=0; i<N; i++){
   fscanf(stdin, "%d", &A[i]);
   printf( "A[%d] is: %d\n", i, A[i]);
}
M.A.K. Ripon
  • 2,070
  • 3
  • 29
  • 47
1

Here is an example taken from http://www.cplusplus.com/reference/cstring/strtok/ that I've adapted to our context.

It splits the str chain in sub chains and then I convert each part into an int. I expect that the entry line is numbers seperated by commas, nothing else. Size is the size of your array. You should do scanf("%d", &size); as Denilson stated in his answer. At the end, you have your int array with all values.

int main(){
  int size = 5, i = 0;
  char str[] ="10,20,43,1,576";
  int list[size];
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str,",");
  list[i] = atoi(pch);
  i++;
  while (pch != NULL)
  {
    pch = strtok (NULL, ",");
    if(pch != NULL)
      list[i] = atoi(pch);
    i++;
  }

  for(i=0;i<size;i++){
    printf("%d. %d\n",i+1,list[i]);
  }
  return 0;
}
Lunfel
  • 2,499
  • 21
  • 29
0

scanf() is kind of a pain in the neck. Check out strtol() for this kind of problem, it will make your life very easy.

vasanth
  • 715
  • 10
  • 23
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
-2

This code employs a straight forward approach of reading each character through getchar().We go onto reading a number util we find a blank space.The index 'i' of the array gets updated after that.This is repeated until newline('\n') is encountered

#include<iostream>
main()
{
  char ch;
  int arr[30] ;
  ch =getchar();
  int num = 0;
  int i=0;
  while(ch !='\n')
  {
    if(ch == ' ')
    { 
      arr[i] = num;
      i++;
      num = 0;
    }
    if(((ch -48) >=0) && (ch-48 <=9))
      num = (num*10) + (ch - 48);
    ch = getchar();   
  }
  arr[i] = num;
  for(int j=0;i<=i;j++)
     std::cout<<arr[i]<<" ";
 }
wahid_abdul
  • 156
  • 2
  • 9
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read this https://stackoverflow.com/help/how-to-answer – S.R Jun 17 '17 at 17:43
  • 1
    This approach fails when numbers are negative or begin with a `'+'`. It is not C code. – chux - Reinstate Monica Jan 30 '18 at 23:57