Sunday 15 May 2011

math - C - Reading arithmetic operators with sscanf -


I am reading a string with two-digit arithmetic operators, just like any of these: A1 + B1 A1 - B1 A1 * B1 A1 / B1

I can read A1 and B1 but not operator. I am reading it using:

  while sscanf (matrix [i] [c] + offset, "% c% d% * c% n", and column, And line, & amp; readCharCount) == 2) {// do something}   

What can I do to read the operator? Unlike the digital conversion specifiers and % s , % c

The conversion specifier does not leave the spaces. Thus, your example inputs are given, reading blank before the % * c operator. You can use wisely:

  while (sscanf (matrix [i] [c] offset, "% c% d% c% c% d", & amp; col1, & Amp; ROW1,   

Since you were using offsets and while capturing when the scan ended, you would use it:

  while ( Sscanf (matrix [i] [c] + offset, "% c% d% c% c% d% n", and call 1, & amp; line 1, and op, and call 2, and line 2, & read chargecount) == 5) ... data is ok ...   

Note that % n does not count the conversion specifier Therefore, test runs against 5, not 6. 6.

Also note that the careful appointment of the empty space in the format string is necessary and flexible (that is, A1 + B2 is OK, as well as handles A1 + B2 ). If you are going to allow large spreadsheets, you can specify:

  while sscanf (matrix [i] [c] + offset, "% 4 [a-zA-Z]% d% c% 4 [a-zA-Z]% d% n", col1, & Amp; ROW1, & amp; Op, col2, & amp; Line 2, & amp; ReadCharCount) == 5) ... data is OK ..   

Where col1 and col2 varies from one to the char col1 [5]; Four coal 2 [5]; (This is why & amp; was also dropped) allows the recognition of such a scan set as aAa1 + BbB2 . Due to the % d notation, the space is allowed between letters or letters and numbers (hence the code aaa 999 + bbb 888 ). (Sscanf (matrix [i] [c] + offset, "% 4 [a-zA-Z]% 5 [0-9] % C% 4 [a-zA-Z]% 5 [0-9]% n ", col1, ROW1, & op, col2, line2, & readCharCount) == 5) ... data is fine ...

where the types are now four line 1 [6]; four row 2 [6]; and the ampersons are removed again Then, convert row1 and row2 into numbers with confidence.

See also: To convert column numbers into related alphabetical codes.

No comments:

Post a Comment