I’m new to C, and I’m trying to scan a line from stdin and extract the nth word from it.
Right now I’ve hard-coded it where you can store the first, second, or third entry in the sentence, and this is what it looks like:
int set_to_nth_word(char* word, char* input, int n)
{
char word1[20];
char word2[20];
char word3[20];
if(sscanf(input, "%s %s %s", word1, word2, word3) < n)
{
printf("You didn't enter enough values\n");
return 0;
}
else
{
if(n == 1) strcpy(word, word1);
else if(n == 2) strcpy(word, word2);
else if(n == 3) strcpy(word, word3);
return 1;
}
}
The code that calls this method is:
char *input = (char *) malloc (1);
if(getline(&input, (size_t)0, stdin) != -1)
{
char word[20];
if(set_to_nth_word(word, input, 1))
{
printf("Success");
}
}
Besides finding a solution to this problem, I’d be happy if anyone points out any bad style or bad coding practices!
You can make use of
%nconversion specifier supported bysscanf(). It requires anint *parameter, and returns the number of characters consumed from the input into thatint.As far as style goes, you should make the
inputparameterconst char *, since the characters pointed to are not being modified in the function.In terms of safety,
wordshould be allocated with a length ofstrlen(input) + 1, rather than declared as a fixed-size array, since the words may be up to that length.