Home > Mobile >  Strange behavior using CString in swscanf directly
Strange behavior using CString in swscanf directly

Time:09-23

I have one problem with CString and STL's set.
It looks a bit strange to use CString and STL together, but I tried to be curious.
My code is below:

#include "stdafx.h"
#include <iostream>
#include <set>
#include <atlstr.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    wchar_t line[1024] = {0};
    FILE * pFile = _wfopen(L"F:\\test.txt", L"rt");

    set<CString> cstr_set;

    while (fgetws(line, 1024, pFile))
    {
        CString cstr;
        swscanf(line, L"%s\n", cstr);
        cstr_set.insert(cstr);
    }

    fclose(pFile);
    cout << "count" << cstr_set.size();
    return 0;
}

The contents of the test.txt is:

13245  
123  
2344  
45  

After the loop ends, cstr_set contains only one value.
It works as if cstr is static or const variable.
What is the problem?

CodePudding user response:

A CString is a Microsoft implementation wrapping a character array into a C object to allow simpler processing.

But, swscanf is a good old C function that knows nothing about what a CString is: it just expects its arguments to be large enough to accept the decoded values. It should never be directly passed a CString.

The correct way would be:

...
#include <cstring>
...
while (fgetws(line, 1024, pFile))
{
    line[wcscspn(line, L"\n")] = 0;  // remove an optional end of line
    CString cstr(line);
    cstr_set.insert(cstr);
}
...
  • Related