gpt4 book ai didi

c++ - 对包含特殊字符的二维数组进行排序 C++

转载 作者:行者123 更新时间:2023-11-28 08:02:23 25 4
gpt4 key购买 nike

我想对这个数组进行排序,但是如果我不在数组中放置任何带有特殊字符的字符串,这段代码就可以工作。如果我有类似的东西

!\"#$%&'()*+,-./0123456789:;<=>?@

它不会工作。它在 Visual Studio 中崩溃。

代码如下:

#include <iostream>
#include <cstring>

using namespace std;

int main (){

char data[10][40] = {
"",
"Welcome",
" !\"#$%&'()*+,-./0123456789:;<=>?@",
"aBCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`",
"abcdefghijklmnopqrstuvwxyZ{||||||||||}",
"CD_ROM",
"ROM",
"SCS",
"3.5 Floppi",
""
};


cout<<"Printing the array as is"<<endl<<endl;

for (int i=0; i<10; i++){
cout<<data[i]<<endl;
}

cout<<endl<<"Ordering the data in Alphabetical order"<<endl<<endl;


// bubble sort

for (int i=0 ; i<10-1 ; ++i) {
char Tcopy[17];
for (int j=i+1 ; j<10 ; ++j) {
if (strcmp(data[i], data[j]) > 0) {
strcpy(Tcopy, data[i]);
strcpy(data[i], data[j]);
strcpy(data[j], Tcopy);
}
}
}


cout<<"Printing the array Sorted"<<endl<<endl;

for (int i=0; i<10; i++){
cout<<data[i]<<endl;
}


// Pause
cout<<endl<<endl<<endl<<"Please Close Console Window"<<endl;
cin.ignore('\n', 1024);
return(0);
}

最佳答案

char data[10][40]

char Tcopy[17];

strcpy(Tcopy, data[i]);

这是你的问题。您的 Tcopy 数组太短。您正在(可能)将 40 个字符复制到 17 个字符的数组中。您正在覆盖缓冲区的末尾,导致谁知道会发生什么损坏。

尝试:

char Tcopy[40];

关于c++ - 对包含特殊字符的二维数组进行排序 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11090872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com