We help IT Professionals succeed at work.

sscanf and CString - why don't it work?

dclaydon
dclaydon asked
on
G'Day all

Why does this code not work?

  CString text;
  int a;
  CString b;

  file->ReadString(text);

  sscanf(text, "%i\t%s", a, b);

What happens is an Access violation error.

'file' is a CStdioFile that has been opened correctly.

text is reading correctly (contains that text "1  fred").

If I change 'a' to be a CString and modify the sscanf appropriately, 'a' and 'b' both become the last string that was scanned.

This program is being written using MS VC++ ver4.2 under Win NT 4.0.

How do I get around this, such that both objects are read correctly?

Regards
Dave
Comment
Watch Question

In function sscanf, you need to use the address of a : &a .
Moreover, you need allocate memory for  the internal character buffer of CString object b.

Here is fix code

      CString text;
      int a;
      CString b;

        file->ReadString(text);
     
        // allocate 500 characters  for b
        sscanf(text, "%i\t%s",  &a,   b.GetBuffer( 500 ));

       b.ReleaseBuffer( ); // update b

Author

Commented:
It fixed the bug.

I always seem to forget the & with scanf functions.

CStrings have some quirks with them (which most people forget).

Thanks