Taking input on 1 line separated by spaces

manjotpahwa's Avatar, Join Date: Apr 2010
Light Poster
How can we make the compiler understand that it has to take input for different cases on one line, e.g.

Enter the information for the three nodes you want to add on the tree
10 15 22

How do we make the computer understand that it has three inputs now, and how to differentiate between them?
0
virxen's Avatar, Join Date: Nov 2009
Pro contributor
Code:
#include <stdio.h>

int main(){
    int number1,number2,number3;
    printf("enter 3 numbers seperated with space:");
    scanf("%d %d %d",&number1,&number2,&number3);
    getchar();//stdin garbage collector
    printf("number1=%d number2=%d number3=%d",number1,number2,number3);
    getchar();//pause
    return 0;
}
if you want something different tell me.
0
manjotpahwa's Avatar, Join Date: Apr 2010
Light Poster
What if the number of arguments are not fixed?
e.g.

Enter the number of test cases:
//The user enters to his own will at that time.
//Then we take the input.

I was thinking more of making a buffer and then trying to read input...
0
virxen's Avatar, Join Date: Nov 2009
Pro contributor
one way to do this is

Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MaxVariable 30//maximum length of a variable is 30 characters
#define BUFFER 200//maximum line length is 200 characters per line
void getString(char *,int);//gets input into our buffer


int main(){
    char Input[BUFFER];
    int count=0;
    char delims[] = " ";//variables are separated by space character
    char *result = NULL;
    char **Variables=NULL;
    printf("\nenter values:");
    getString(Input,BUFFER);//we input our string into buffer
    printf("\nyou entered:%s\n",Input);
    printf("splitting input\n");
    result = strtok( Input, delims );//we divide our input string into pieces based on spaces
    while( result != NULL ) {
         Variables=(char **)realloc(Variables,(count+1)*sizeof(char *));
         Variables[count]=(char *)malloc(MaxVariable*sizeof(char));
         Variables[count++]=result;
         result = strtok( NULL, delims );
     }
     for (int i=0;i<count;i++)
         printf("\n variable %d=%s",(i+1),Variables[i]);//we print our variable array
    getchar();
    return 0;
}


void getString(char *string,int buffer){
    int i=0;
    fgets ( string, buffer, stdin );
    for ( i = 0; i < buffer; i++ ){
        if ( string[i] == '\n' ){
            string[i] = '\0';
            break;
        }
    }
}
all variables are input as strings.

use atoi to convert into integers.
but after you check it ,,if it's really an integer.