0

On this StackExchange topic, first answer and last comment upon that answer, I learned to assign the contents of my char array (which I just read from file) into my vector. The following code works fine in Windows XP, 32-bit, Visual Studio 2010, but fails in Win10, 64-bit, Studio 2012. Both projects use the Unicode character set. The contents of the file myConfig.txt are (separated by tabs):

words 3 mobius lagrange gauss

I am a complete noob, so if some mistake seems too stupid for anyone to make, go ahead and assume I made it.

The code:

#include "stdafx.h"
#include <windows.h>
#include <vector>
#include <iterator>     
#include <string.h>
#include <wchar.h>
#include <tchar.h>

using namespace std;

vector<wchar_t> wvec;
int n;
wchar_t ss[256];
FILE* pfile;

int _tmain(int argc, _TCHAR* argv[])
{
    fopen_s(&pfile,"myConfig.txt","r");
    fwscanf_s(pfile,L"%ls",&ss);
    wprintf(L"var name is %ls\n",ss);
    fwscanf_s(pfile,L"%d",&n); 
    printf("num words is %d\n",n);
    for (int i=0; i<3; i++) {
        fwscanf_s(pfile,L"%ls",&ss);
        wvec.clear();
        n=wcslen(ss);
        wprintf(L"vec empty %ls length %d\n",vec,vec.size());
        wvec.assign(ss,ss+n+1); // +1 to contain null char
        wprintf(L"vec sz %d filled %ls\n",wvec.size(),wvec);
    }
    printf("press Enter to finish\n");
    getchar();
    return 0;
}

On the Win10 machine, the output says, in part, "vec sz 7 filled ???", when I run/debug from the development environment. When I run the exe in the x64\Release folder, the corresponding line of output says "vec sz 5 filled ???", while the contents of myConfig.txt are exactly the same.

On the XP machine, the output is perfect.

Community
  • 1
  • 1

1 Answers1

0

Finally answered my own question: RTFM. It should not be

fscanf_s(pfile,"%s",&s);

It should be

fscanf_s(pfile,"%s",s, _countof(s));

I dunno why it worked in XP (convenient #bytes/char?) but, whatever.