Hey, folks!
I'd appreciate if you could review my solution to the following exercise for correctness. I've tested it for several different input and sequential calls, and I couldn't spot any obvious bugs. Any suggestions for improvement are welcome!
Exercise
"Design and test a function that reads the first word from a line of input into an array and discards the rest of the line. Define a word as a sequence of characters with no blanks, tabs, or newlines in it." (I've added three features the exercise does not explicitly ask for -- array is always null-terminated, bsize (buffer size) is passed as an argument to the function, and function returns the number of characters read.)
My solution
Code:
#include <stdio.h>
#include <ctype.h>
int msh_getw(char* buffer, int bsize) {
int cnt = 0;
while (cnt < bsize) {
*buffer = getchar();
if ( isspace(*buffer)) {
*buffer = '\0';
while( getchar() != '\n');
return cnt;
}
cnt++;
buffer++;
}
*(buffer - 1) = '\0';
while( getchar() != '\n');
return cnt;
}
Thanks for you time!