简体   繁体   English

C++ wstring - 读取字符串字符时出错 | 发生在第 10 个字符之后

[英]C++ wstring - Error reading characters of strings | Happens after the 10th character

I am asking for information to save onto the database like their username and stuff, you can use up to 10 characters perfectly fine, the wstring holds it and I can use it how I like, but if a user were to type 11 characters it would all of a sudden say "Error reading characters of strings" .我要求将信息保存到数据库中,例如他们的用户名和内容,您最多可以使用 10 个字符, wstring保存它,我可以按照自己的喜好使用它,但是如果用户要输入 11 个字符,它会突然说"Error reading characters of strings"

At first I thought I didn't have a big enough space for GetWindowText so I pumped that up, I didn't know if you can change the wstring capacity so that is why I am asking here.起初我以为我没有足够大的空间来容纳GetWindowText所以我把它抽了起来,我不知道你是否可以改变wstring容量,所以这就是我在这里问的原因。

Why is wstring only working with 10 or less characters?为什么wstring只能使用 10 个或更少的字符? Thanks!谢谢!

case WM_COMMAND: {

    switch (LOWORD(wParam))
    {
        case IDB_REGISTERACCOUNT: {
            std::wstringstream SQLStatementStream;
            std::wstring SQLUsername;
            std::wstring SQLPassword;

            //Get user information than store in wide Strings
            GetWindowText(hUserNameRegister, &SQLUsername[0], 50);
            GetWindowText(hPasswordRegister, &SQLPassword[0], 50);

            std::wstring SQLStatement = SQLStatementStream.str();

            break;
        }
    }
    break;
}

Your code is essentially saying, "I am giving you the address of the first character of this string, start writing to it indiscriminately."你的代码本质上是在说,“我给你这个字符串的第一个字符的地址,开始不加选择地写入它。” This is going to be a bad time.这将是一个糟糕的时期。 What you need to do is first allocate an actual buffer to use to store the result, then if you wanted in the wstring, you can use the wstring's '=' operator to do the proper assignment.您需要做的是首先分配一个实际缓冲区用于存储结果,然后如果您想要在 wstring 中,您可以使用 wstring 的 '=' 运算符进行正确的分配。

something like:就像是:

WCHAR temp[50];
GetWindowText(hUserNameRegister, temp, 50);
SQLUsername = temp

You write past the end of your string.你写过字符串的结尾。 This causes undefined behaviour.这会导致未定义的行为。

Only use &x[0] on a standard library string when you are in read-only mode, or if you are writing but not going to change the length of the string.当您处于只读模式时,或者您正在编写但不打算更改字符串的长度时,仅在标准库字符串上使用&x[0]

You should have written:你应该写:

wchar_t SQLUsername[50] = {};
GetWindowTextW(hUserNameRegister, SQLUsername, 50);

Then you can convert to wstring if you wanted with std::wstring wsSQLUsername = SQLUsername;然后你可以转换为wstring如果你想要std::wstring wsSQLUsername = SQLUsername; - however your code never actually uses your wstring s before they go out of scope so perhaps you have some other misconceptions too. - 但是,您的代码在超出范围之前从未实际使用您的wstring ,因此您可能还有其他一些误解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM