Ignoring leading whitespace with character array in C
I'm using the fgets function to read a line from a file. I don't underst开发者_JS百科and how to ignore the leading whitespace of a file though. I thought if I had a char array I could check the first value to see if it is whitespace with isspace, and then increment to the next value. My code looks like:
while (!feof(fp)) {
fgets(str, LINE_SIZE, fp);
while (isspace(*str)) { // need help
str + 1; // here
}
for (cp = str; cp = strtok(cp, "AEIOUaeiou\n"); cp = NULL) {
puts(cp);
}
}
}
Thanks!
what you want is something like
while (!feof(fp)) {
fgets(str, LINE_SIZE, fp);
char * tmp = str; //use a temporary variable so str pointer isn't overwritten
while (*tmp && isspace(*tmp)) { // need help
tmp++; // here
}
for (cp = tmp; cp = strtok(cp, "AEIOUaeiou\n"); cp = NULL) {
puts(cp);
}
}
}
the value of str was not modified. try to change
str+1;
to
str++;
You should use
str = str+1;
which can be shorten to
str += 1;
or even better
++ str;
in // here
to update the pointer str
.
Your code has some issues:
Most of the times, you don't want to do the check feof(fp)
at the top of a loop when reading a file. It is almost guaranteed that if you do so, you will read the last line of the file twice. This is because feof()
returns true only if an earlier read attempt resulted in "end of file". Better method is to check if fgets()
returns NULL
:
while (fgets(str, LINE_SIZE, fp) != NULL) {
/* do your processing */
}
if (ferror(fp)) { /* there was an error reading some data */ }
Your isspace()
call should cast *str
to unsigned char
if it is not of that type:
while (isspace((unsigned char)(*str))) {
To use isspace()
, you should #include <ctype.h>
.
You need to increment str
. Your expression str+1
evaluates str+1
, discards its value, and does nothing. So, you need:
++str;
But you don't want to increment str
: you need that for the next fgets()
call. So, you should copy it to a temporary pointer:
char *tmp = str;
while (isspace((unsigned char)(*tmp))) {
++tmp;
}
Making all the changes above, your loop becomes:
while (fgets(str, LINE_SIZE, fp) != NULL) {
char *tmp = str;
while (isspace((unsigned char)(*tmp)))
++tmp;
for (cp = tmp; cp = strtok(cp, "AEIOUaeiou\n"); cp = NULL) {
puts(cp);
}
}
(You have an extra closing }
, most likely a copy-paste error.)
To add to Kenny and Piere since they have mentioned str++
and ++str
, the difference between the two is which version of str
will be used in the expression.
For example
int y=1;
x[y++]=10; //1
and x[++y]=10; //2
in //1
index 1 is used and x[1]
is assigned 10 and after that y is 2
and in //2
x[2]=10
meaning that y was incremented before it was used as an index.
Generally you want to use ++value
everywhere. However as I have illustrated value++
has its uses.
精彩评论