[英]What is the problem with the following code using constructors for sorting strings?
#include <iostream>
#include <string.h>
using namespace std;
class sorting
{
private:
char str[10];
public:
sorting() {
int i;
for(i=0;i<10;i++) {
cin>>str[i];
}
}
void sort() {
int i,j;
char temp;
for(i=0;i<10;i++) {
for(j=i+1;j<10;j++) {
if(strcmp(str[j],str[j+1])>0) {
strcpy(temp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],temp);
}
}
}
for(i=0;i<10;i++) {
cout<<str[i];
cout<<"\n";
}
}
};
int main() {
sorting s1;
cout<<s1.sort();
return 0;
}
这是我编写的使用构造函数对字符串进行排序的代码。 它在我使用 strcmp 的代码的 if 条件中给了我错误。 请查看此内容,因为我无法获得所需的输出并且它给了我错误。
就像有人已经指出的那样,您不能在字符上使用strcopy
。 如果你想创建一个字符串数组,我建议使用char**
或std::string*
。
在您的嵌套循环中,您将得到一个index out of bounds
错误,因为一旦i
达到8
的值, j
将是9
,这意味着当您尝试访问str[j+1]
,它的计算结果为str[10]
,你会得到所说的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.