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

≯℡__Kan透↙ 提交于 2019-11-27 08:59:16
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 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;
}

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

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