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?
|
Pro contributor
|
![]() |
| 17Apr2010,01:37 | #2 |
|
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;
}
|
|
Light Poster
|
|
| 17Apr2010,02:00 | #3 |
|
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... |
|
Pro contributor
|
![]() |
| 17Apr2010,04:15 | #4 |
|
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;
}
}
}
use atoi to convert into integers. but after you check it ,,if it's really an integer. |

