开发者

C, reading multiple numbers from single input line (scanf?)

开发者 https://www.devze.com 2022-12-25 13:51 出处:网络
I have written an app in C which expects two lines at input. First input tells how big an array of int will beand the second input contains values separated by space.

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.


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()


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]);
}


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;
}


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


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]<<" ";
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号