c++字符串截取放入容器,输出乱码

字符串截取放入容器,输出乱码

#include 
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main() {
    string str = { "1#张飞#赵云#关羽" };
    map<int, vector>m;
    vectorv;
    char a = '#';
    int i = str.find(a, 0);
    string str1 = str.substr(0, i);
    int key = atoi(str1.c_str());
    for (int j = i; j < str.size(); j++)
    {
        if (int z = str.find(a, i)) {
            v.push_back(str.substr(j, z));
        }
    }
    m.insert(make_pair(key, v));
    for (map<int, vector>::iterator it = m.begin(); it != m.end(); it++)
    {
        cout << it->first << " ";
        for (vector::iterator pos = it->second.begin(); pos != it->second.end(); pos++)
        {
            cout << *pos << " ";
        }
        cout << endl;
    }
    system("pause");
    return 0;

}

该回答通过自己思路及引用到GPTᴼᴾᴱᴺᴬᴵ搜索,得到内容具体如下:
在您的代码中,出现乱码的原因是因为使用了 string::substr 函数截取子字符串时没有考虑到字符串的编码格式,导致输出时出现乱码。

在默认情况下,string 类使用的是 ASCII 编码格式,而在您的字符串中可能包含了中文字符,因此需要使用 Unicode 编码格式才能正确地输出中文字符。

为了解决这个问题,您可以将程序中的 cout 语句替换为以下代码:

wcout.imbue(locale("chs"));
wcout << it->first << " ";
for (vector<string>::iterator pos = it->second.begin(); pos != it->second.end(); pos++)
{
    wcout << wstring(pos->begin(), pos->end()) << " ";
}
wcout << endl;

这里,我们首先使用 imbue 函数设置输出流的本地化参数为 "chs",即使用中文编码格式。然后,使用 wstring 类型将 vector<string> 中的子字符串转换为宽字符,以便在控制台中正确地输出中文字符。

希望这个解决方案能够帮到您!


如果以上回答对您有所帮助,点击一下采纳该答案~谢谢

  • 帮你找了个相似的问题, 你可以看下: https://ask.csdn.net/questions/7527706
  • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:c++字符串处理、输入流和输出流
  • 除此之外, 这篇博客: C++输入输出优化中的 输出优化 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • inline void write(int x)
    {
    	int y=10,len=1;
    	if(x<0)
    	{
    		x=-x;
    		putchar('-');
    	}
    	while(y<=x)
    	{
    		y*=10;
    		len++;
    	}
    	while(len--)
    	{
    		y/=10;
    		putchar(x/y+48);
    		x%=y;
    	}
    }

    ———————————————————————————————————————————————————————

    还有让cin和cout与scanf和printf差不多快的语句

    ios::sync_with_stdio(false);

    将上述语句加在cin/cout前面就能大大加快cin/cout的速度

  • 您还可以看一下 夏浡源老师的C++入门基础视频精讲课程中的 输入输出小节, 巩固相关知识点