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

自作多情 提交于 2019-11-26 11:23:45

问题


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.


回答1:


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




回答2:


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



回答3:


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



回答4:


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




回答5:


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


来源:https://stackoverflow.com/questions/2539796/c-reading-multiple-numbers-from-single-input-line-scanf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!