c++读取 config.ini配置文件能读取中文吗
时间: 2023-08-01 16:14:20 浏览: 79
使用标准库 \<fstream\> 和 \<sstream\> 读取配置文件时,可以读取中文,但需要注意编码问题。
假设配置文件 config.ini 的内容如下:
```
[database]
host = localhost
port = 3306
username = root
password = 123456
```
如果配置文件是以 UTF-8 编码保存的,可以使用以下代码读取配置文件:
```c++
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
int main() {
std::ifstream fin("config.ini");
std::map<std::string, std::map<std::string, std::string>> config;
std::string line;
std::string section;
while (std::getline(fin, line)) {
std::istringstream iss(line);
std::string key, value;
if (line[0] == '[' && line.back() == ']') {
section = line.substr(1, line.size() - 2);
} else if (std::getline(iss, key, '=') && std::getline(iss, value)) {
config[section][key] = value;
}
}
// 输出读取结果
for (const auto& section : config) {
std::cout << "[" << section.first << "]" << std::endl;
for (const auto& key_value : section.second) {
std::cout << key_value.first << " = " << key_value.second << std::endl;
}
std::cout << std::endl;
}
return 0;
}
```
这段代码与前面介绍的代码类似,只是没有使用第三方库。需要注意的是,配置文件的编码需要与程序所使用的编码一致,否则读取中文可能会出现乱码。如果配置文件使用的是其他编码格式,需要先将其转换为 UTF-8 编码。