Getting a string from serial with "scanf"

Hello there:

I am having some problems using scanf to get a string of 22 characters from a serial port.

I think the problem is that the string has some blank characters on it, so scanf will stop in each blank character and get 2 or 3 strings instead of only 1.

The string is something like this "N____0.000_g__CRLF" where the '_' are blank characters (20 hex).

Now with scanf I am getting something like this:

N

0.000

g

I have sorted this problem with a for loop and getc() but I prefer to do it with scanf.

Is there any way to indicate scanf that the string will length 22 characters and get the 22 in a shot??

Regards,

Rafa.

17 Nov 2010 . Edited: 17 Nov 2010

Show us your code with the scanf call.

Edit: actually, I think what you want is "%22c". But it's a pretty ineffective way of using scanf. Why not tell it to parse the line for the data that's in there (e.g. the number)?

17 Nov 2010 . Edited: 17 Nov 2010

Ok, here it is a bit of the code:

int main() {

    serie_bal.baud(19200);

    while (1) {

        serie_bal.scanf("%s\n", &strBalanza);//Capturamos cadena de balanza

.....

I receive a 22 characters string every 100ms, and because scanf is a blocking function (i think) it would be perfect to catch the string with it. (it will wait until a string comes in).

With this code, it works, but the problem is that the scanf catches a string every blank character it founds. If the string wouldnt have blank characters it would run perfect. I need advise on how to get the entire string (22characters) with blank spaces and all.

Hope you can help me.

Regards.

EDIT:

I have tried %22s, will try %22c to see if it works. Sorry but i dont know what is "to parse". My english is so limited. BTW, I need all the information in the string, because it depends on how many blank characters are there to do one or other thing later...

08 Jul 2011

why dont you replace the "_" (blank) with a comma?

08 Jul 2011

I wouldn't use scanf at all. If there are line breaks and reasonable line lengths I would use fgets. If it is really just characters in blocks of 22, I would use fgetc or even fread. Since there are spaces in your data, it suggests that there is an underlying structure, in that case I would first get the sting (22 chars) and then use sscanf to parse the string. scanf just does not do well with unexpected input.