Search code examples
cstringinputenter

how to take input from space separated integers in c/c++?


first line contains an integer N. Each of the next N lines contains at least 1 and at most 100 space separated distinct integers(DEPENDS ON USER CHOICE). For ex-

3
5 100 1
2
5 100

i want to store nos in a 2d array like
a[1][1] = 5 , a[1][2] =100, a[1][3] = 1
a[2][1] =2
a[3][1] = 5, a[3][2] = 100


Solution

  • In C, you can use the strtok() function.

    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
       char str[80], first[12];
       char *token;
       int num, n, i;
       int ara[100][100]; // whatever size you want
    
       get(first);
       n = atoi(first);
    
       for (i = 1; i <= n; i++) {
         gets(str);
         token = strtok(str, " ");
    
         while( token != NULL ) 
         {
            num = atoi(token);
            printf( "%d\n", num );
    
            token = strtok(NULL, " ");
         }
       }
    
       return 0;
     }