简体   繁体   English

从 .ini 文件中获取字符串

[英]Getting a string from .ini file

Getting a string from .ini file for login not working.从 .ini 文件中获取用于登录的字符串不起作用。 Please don't suggest one of those phases or anything.请不要建议这些阶段之一或任何东西。 Unless this won't work.除非这行不通。 B

char* pResult = new char[255];
GetPrivateProfileString("login", "uname", "", pResult, 255, "C:\\Program Files\\myfile\\login.ini");
if (pResult == "1"){
    g_pCVar->ConsoleColorPrintf(Color::Purple(),
        "----Login-Succesfull----\n");

}

else{
    g_pCVar->ConsoleColorPrintf(Color::Purple(),
        "----Login-Failed----\n");

}
delete[] pResult;

Here is the .ini file.这是 .ini 文件。

[login]
uname=1

Could someone please suggest what the issue is.有人可以建议问题是什么。 Could it be because I am reading from programs files.可能是因为我正在读取程序文件。 I had an issue when I was reading from temp?我从 temp 读取时遇到问题? Thanks.谢谢。

if (pResult == "1")

This is wrong, here you compare the pointers, not the actual data pointed by those.这是错误的,在这里您比较的是指针,而不是指针所指向的实际数据。 You should use something like if (std::strcmp(pResult,"1") == 0) ( strcmp is case sensitive)您应该使用类似if (std::strcmp(pResult,"1") == 0)strcmp区分大小写)

In windows there's also a _stricmp (case insensitive).windows还有一个_stricmp (不区分大小写)。

I remember back in the day I wrote a small helper like this one:我记得那天我写了一个这样的小帮手:

std::string get_profile_string(LPCSTR name, LPCSTR key, LPCSTR def, LPCSTR filename)
{
    char temp[1024];
    int result = GetPrivateProfileString(name, key, def, temp, sizeof(temp), filename);
    return std::string(temp, result);
}

If small string optimization is enabled, it will be used if result is small enough (so no memory allocation would happen).如果启用了小字符串优化,如果result足够小(因此不会发生内存分配),则会使用它。 There's a limit of 1024 chars, which you can increase if you need of course.有 1024 个字符的限制,如果您需要,当然可以增加。

The std::string class overloads the equal to == operator so this time if (pResult == "1") will actually work. std::string类重载了等于==运算符,因此这次if (pResult == "1")将实际起作用。

string result = get_profile_string("login", "uname", "", "C:\\Program Files\\myfile\\login.ini");

if (result == "1")
    g_pCVar->ConsoleColorPrintf(Color::Purple(), "----Login-Succesfull----\n");    
else
    g_pCVar->ConsoleColorPrintf(Color::Purple(),"----Login-Failed----\n");

But ideally, if you simply want an integer, then you shouldn't use GetPrivateProfileString at all.但理想情况下,如果您只是想要一个整数,那么您根本不应该使用GetPrivateProfileString Instead, use GetPrivateProfileInt相反,使用GetPrivateProfileInt

int age = GetPrivateProfileInt("user", "age", 0, "C:\\Program Files\\myfile\\login.ini");

if (age >= 18)
{ }    
else
{ }

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

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