read next word in C

So I have to code a function that will get the next word from the standard output and this is what I have. It need to skip any leading character that is non-alphanumeric. return the word or null of it find EOF. the thing is I am in a endless loop, it never returns NULL. Any help will be greatly appreciated


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
char buf[MAXBUF];
int c;
int x = 0;

do {
c = getchar();
} while(!isalnum(c));

while(c != EOF){
if(isalnum(c)){
buf[x] = c;
x++;
c = getchar();
} else {
return make_string(buf, x);
}
}

return NULL;
Don't loop on EOF. Input loops should (unless you know exactly why) be of the form:

1
2
3
4
5
6
while (TRUE)
{
  try to get input;
  if (error or EOF) break;
  process input;
}

In your code on lines 5..7, you may read an EOF, but EOF will never be an alphanumeric, so the loop will continue forever.

There is no simple one-liner for this in C.

Hope this helps.
yes I see what you mean. I did that so I can skip any non-alphanumeric character that comes before the first character

thank you
use gets();// and EOF is for file
int main()
{
char s[101];

cout<<"Please input something:"<<endl;;
while (gets(s)!=NULL)
{
if(s[0]=='\0')
{
break;
}
puts(s);
}

return 0;
}
Never use gets().
Topic archived. No new replies allowed.