这可能是一个愚蠢或奇怪的问题,但我在程序中的字符串遇到了一些奇怪的事情。这是我的完整代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
struct Word{
private:
wchar_t wrd[32];
public:
wchar_t pword[32];
void _assign(wchar_t* sender)
{
memcpy(wrd, sender, sizeof(sender)+1);
memcpy(pword, wrd, sizeof(wrd)+1);
}
};
int main(void)
{
HANDLE ConsCL = GetStdHandle(STD_OUTPUT_HANDLE);
printf("%s", "Dic size: ");
int tam;
scanf("%i", &tam);
wchar_t* dic[tam];
Word words[tam];
for(int i=0; i<tam; i++)
{
printf("Add word %d: ",(i+1));
dic[i] = (wchar_t*)malloc(33);
scanf("%s", dic[i]);
words[i]._assign(dic[i]);
}
system("CLS");
printf("%s", "Succesfully stored dictionary\nBegin writting a word: \n ");
int cont=0;
for(int i=0; i<tam; i++)
{
printf("%s\n", words[i].pword);
}
//wchar_t* _tword;
char w = _getch();
for(int i=0; i<tam; i++)
{
if(toupper(w)==toupper(words[i].pword[0]))
cont++;
}
printf("%c\n", w);
wchar_t* _final[cont];
for(int i=0; i<cont; i++)
{
if(toupper(w)==toupper(words[i].pword[0]))
_final[i] = words[i].pword;
}
//system("CLS");
for(int i=0; i<cont; i++)
{
printf("%s\n", _final[i]);
}
/*SetConsoleTextAttribute(ConsCL, (FOREGROUND_RED | FOREGROUND_INTENSITY));
printf("%c", w);
SetConsoleTextAttribute(ConsCL, (FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY));
printf("%c", 'f');*/
return 0;
}
但是当我添加一些单词时,它会改变一些值。例如,查看此示例及其输出:
Dic Size: 5
Add word 1: perro
Add word 2: perra
Add word 3: persona
Add word 4: santuario
Add word 5: sanitario
OUTPUT:
perro
perra
persona
santuario´ //Why it show that symbol??
sanitario
所以如果我这样说
Dic size: 1
Add word 1: santuario
OUTPUT:
santuario
或者,如果我添加很多单词,有时会将单词大小写更改为大写等。 wchar_t 发生这种情况是否有原因?如果我将所有 wchar_t* 更改为 char* 并将 wchar_t 更改为 char[32] 它工作得很好... wchar_t 有什么问题?
最佳答案
您遇到多个问题,以下列出了其中的一些问题:
- 在
_assign
中,您在指针上使用sizeof
,这将返回指针的大小,而不是它指向的内容 - 您使用 variable length arrays从技术上讲,这不是有效的 C++
- 当您执行
malloc(33)
时,您会分配 33 个字节,而不是 33wchar_t
- 在
printf("%s\n", Words[i].pword)
中,您使用格式"%s"
,该格式适用于窄字符(即普通字符)char
) 而不是wchar_t
- 与
printf
调用一样,您可以在Scanf
中使用窄字符输入格式 - 与
toupper
相同,它适用于char
而不是wchar_t
最后,您的程序是(大部分)C 和 C++ 的混合体,这只会导致问题。您必须记住,虽然 C++ 与 C 有许多相似之处(因为 C 是 C++ 的祖先),但它们仍然是两种截然不同的语言。如果你想使用C++,那就尽可能地使用。例如,使用 std::wstring
(or std::string
for narrow character strings)而不是字符指针和数组。如果您使用 the C++ standard library 中的类和函数作为一名 C++ 程序员,你的生活将会变得更加轻松。
关于c++ - 存储 wchar_t 并在显示时有时会更改一些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25222942/