Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c - how to ignore whitespaces in fscanf()

I need to use fscanf to ignore all the white spaces and to not keep it. I tried to use something like the combination between (*) and [^ ] as: fscanf(file," %*[^ ]s",); Of course it crashed, is there any way to do it only with fscanf?

code:

int funct(char* name)
{
   FILE* file = OpenFileToRead(name);
   int count=0; 
   while(!feof(file)) 
   {
       fscanf(file," %[^
]s");
       count++;
   }
   fclose(file);
   return count;
}

Solved ! change the original fscanf() to : fscanf(file," %*[^ ]s"); read all the line exactly as fgets() but didnt keep it!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using a space (" ") in the fscanf format causes it to read and discard whitespace on the input until it finds a non-whitespace character, leaving that non-whitespace character on the input as the next character to be read. So you can do things like:

fscanf(file, " "); // skip whitespace
getc(file);        // get the non-whitespace character
fscanf(file, " "); // skip whitespace
getc(file);        // get the non-whitespace character

or

fscanf(file, " %c %c", &char1, &char2); // read 2 non-whitespace characters, skipping any whitespace before each

from:

Ignoring whitepace with fscanf or fgets?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...