I am trying to set variables by using fgetc()
from stdin
.
Here's my code so far,
#include <stdio.h>
int main(void){
int ch;
int firstNumber,secondNumber;
char str;
printf("Enter two numbers and a string: ");
while((ch=fgetc(stdin))!='\n'){
while(ch != ' '){
firstNumber = ch;
secondNumber = ch;
string = ch;
}
}
printf("%d %d %s",firstNumber,secondNumber,string);
return 0;
}
Therefore, if I type 2 2 string
(there's whitespace between characters)
I want variable firstNumber
to be 2
and secondNumber
to be 2
and str
to be string
Here is the possible approach:
- You can parse the entire string first and store it into temporary buffer.
- You can now use
strtok()
to tokenize the string using' '(space)
character. Alternatively, you can usesscanf()
instead ofstrtok()
.- Use
atoi()
for first two numbers and read the final string.
Code:
Assuming that the buffer required to store scanned string doesn't exceed
100
bytes.
Approach using strtok()
:
int main()
{
int ch,i=0;
int firstNumber,secondNumber;
const char seperator[2] = " -";
char buffer[100];
char *string;
printf("Enter two numbers and a string: ");
while((ch=fgetc(stdin))!='\n'){
buff[i++]=ch;
}
/* get the first token as a number */
firstNumber = atoi(strtok(buff, seperator));
printf("%d\n",firstNumber);
/* get the second token as a number*/
secondNumber = atoi(strtok(NULL, seperator));
printf("%d\n",secondNumber);
/* get the third token as a string */
string=strtok(NULL, seperator);
printf("%s\n",string);
return(0);
}
Approach using sscanf()
:
printf("Enter two numbers and a string: ");
while((ch=fgetc(stdin))!='\n'){
buff[i++]=ch;
}
sscanf(buff, "%d %d %s", &firstNumber, &secondNumber, string);
printf("%d\n%d\n%s\n", firstNumber, secondNumber, string);