Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Taking input on 1 line separated by spaces (http://www.go4expert.com/forums/taking-input-1-line-separated-spaces-t21784/)

manjotpahwa 16Apr2010 18:26

Taking input on 1 line separated by spaces
 
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?

virxen 17Apr2010 01:37

Re: Taking input on 1 line separated by spaces
 
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.

manjotpahwa 17Apr2010 02:00

Re: Taking input on 1 line separated by spaces
 
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...

virxen 17Apr2010 04:15

Re: Taking input on 1 line separated by spaces
 
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.


All times are GMT +5.5. The time now is 11:38.