I'm using fgets with stdin to read in some data, with the max len开发者_运维百科gth I read in being 25. With one of the tests I'm running on this code, there are a few hundred spaces after the data that I want - which causes the program to fail.
Can someone advise me as to how to ignore all of these extra spaces when using fgets and go to the next line?
Use fgets()
iteratively, then scan the string to see whether it is all spaces (and whether it ends with a newline) and ignore it if it is. Or use getc()
or getchar()
in a loop instead?
char buffer[26];
while (fgets(buffer, sizeof(buffer), stdin) != 0)
{
...process the first 25 characters...
int c;
while ((c = getchar()) != EOF && c != '\n')
;
}
That code simply ignores all characters up to the next newline. If you want to ensure that they are spaces, add a test in the (inner) loop - but you have to decide what to do if the character is not a space.
Spelling out the suggestion given by Jonathan Leffler about getc():
I assume you have a loop like this:
while (!feof(stdin)) {
fgets(buf, 25, stdin);
...
}
change it like this:
while (!feof(stdin)) {
int read = fgets(buf, 27, stdin);
if (read > 26) { // the line was *at least* as long as the buffer
while ('\n' != getc()); // discard everything until the newline character
}
...
}
Edit: Ah, Jonathan is faster than I am at writing C. :)
Try this code , for removing trailing spaces.
char str[100] ;
int i ;
fgets ( str , 80 , stdin ) ;
for ( i=strlen(str) ; i>0 ; i-- )
{
if ( str[i] != ' ' )
{
str[i+1]='\0';
break ;
}
}
精彩评论