c++ - Exiting While Loop immediately after the last word in a line -
i reading following line file using fgets:
#c 1 2 3 4 5 6 7 8 9 ten eleven
each word (except #c) column heading. there eleven columns in file.
my aim divide line tokens of each word. also, need count there 11 column headings. (there can more or less column headings 11)
my problem spaces @ end of line. here code using:
while(1){ fgets(buffer,1024,filename); if (buffer[1] == 'c'){ char* str = buffer+2; char* pch; pch = strtok(str," "); while(pch != null){ pch = strtok (null, " "); if (pch == null)break; //without this, ncol contains +1 //amount of columns. ncol++; } break; } }
this code gives me ncol = 11. , works fine.(note there single space @ end of line reading)
however, if have no space @ end of line, gives ncol = 10 , not read last column.
my aim ncol =11 regardless of whether there spaces @ end of not. want read last word, check if there more word , if there isn't, exit.
if change loop:
while(pch != null){ pch = strtok (null, " "); if (pch == null)break; //without this, ncol contains +1 //amount of columns. ncol++; }
to:
while(pch != null){ char *keep = pch; pch = strtok (null, " "); if (pch == null) { if (strlen(keep)) { ncol++; } break; //without this, ncol contains +1 } //amount of columns. ncol++; }
so, if there left in string, when pch
null, have string, increement ncol
in if. [you may find if input file not "wellformed" if (strlen(keep))
needs more thorough, i'm assuming input "nice"]
Comments
Post a Comment