I have used fgets() to get the line :
Now you say scan the line using sscanf(), how do you do that?Code:fgets(words, 16, stdin);
Sorry, im new at this.
Printable View
My last reply was some sardonic humor for some of the more advanced folk. My apologies.
Example:
Code:#include <stdio.h>
#include <string.h>
#define MAX_SIZE 16
int main(void)
{
/* char array to hold each word with a max word size of 15 */
char words[MAX_SIZE], line[MAX_SIZE];
printf("Enter a line of text: ");
while(fgets(line, MAX_SIZE, stdin))
/* this loop prints each word one after the other from left to right */
if(sscanf(line, "%s\n", words))
printf("%s\n", words);
return 0;
}
I would suggest that you make that "line" instead of words, and make the line variable say 80-1000 long.
In simple form:
However, you would need to move forward to the next word as you walk the string, so that becomes something like this:Code:sscanf(words, "%s", oneword);
The above code is far from perfect - it will fail for strings that start with spaces, or strings that have words longer than 16 characters.Code:
... // in the variable section of your code:
char *pline;
char line[256];
char aword[16];
...
fgets(line, sizeof(line), stdin);
...
pline = line;
while(sscanf(pline, "%s", aword))
{
pline += strlen(aword);
// process aword.
};
--
Mats
Ah yes. You should swap where my fgets() is and poll feof() instead to control the loop. And as suggested, it wouldn't hurt to make the line array larger than 16 bytes.
You could always use strtok(), too (in conjunction with fgets(), that is). Assuming you don't care about the line as a whole, just about the individual words themselves.
@master5001: note that sscanf() will, when reading a string with %s or %d or any of the normal format specifiers, automatically skip over whitespace. This means that a format string as simple as "%s" would suffice.
I am wondering if the OP doesn't just want to loop through strtok() to get each individual word.
That's kind of what I said. (Though perhaps my post wasn't visible when you wrote yours.)
strtok() might not be the best function around, but it's probably going to be easier than using sscanf() or isspace() etc to walk through the string.
http://www.cplusplus.com/reference/c...ng/strtok.html
Yeah no biggy. Great minds think alike, and I am trying to read a book whilst posting. So my time between writing and submitting is very asynchronous. So it is settled, OP, use fgets() and strtok(). And forget even looping at all, actually. There is no need within the scope of this program.
Well, you pretty much have to loop to keep calling strtok(). (Unless you only care about the first word or something.)