尝试在 c++ 中按字母顺序排列单词时出现分段错误



我是 c++ 的新手,我正在尝试编写一个代码,按字母顺序整理我从控制台给出的一些单词。 我不知道为什么,但我得到分段错误错误。你能帮帮我吗?

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <cstring>
using namespace std;
int arrange (const void * a, const void * b)
{
//return ( *(int*)a - *(int*)b );
return (strcmp(*(const char **)a, *(const char **)b));
}
int main() {
char words[50][50];
int i=0, n;
cout << "Enter the number of words to be ordered:";
cin >> n; 
int length = 0;
for (i=0;i<n;i++) {
cin >> words[i];
cout << words[i];
}
qsort(words, n, sizeof(words[0]), &arrange);
}

这就是我的代码的样子

这更像是一个C问题。 qsort 例程传入两个值:不指向值的指针;因此,您的比较应该是

int arrange (const void * a, const void * b)
{
return (strcmp((const char *)a, (const char *)b));
}

你的代码比C++更像 C。 你应该使用vectorstringsort。 并检查您的输入是否失败。

此外,您的代码应该是可剪切粘贴可编译的。 您缺少标头和using语句。

您对qsort(C 例程(的使用不会以您使用它的方式工作。 C++提供了sort,这更适合您正在解决的问题。

例如。。。

#include <algorithm>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <string>
#include <vector>
using std::begin;
using std::cin;
using std::cout;
using std::end;
using std::ostream;
using std::sort;
using std::runtime_error;
using std::string;
using std::vector;
static ostream& operator<<(ostream& o, vector<string> const& words) {
char const* sep = "";
for(auto const& word : words) {
o << sep << word;
sep = ", ";
}
return o;
}
int main() {
vector<string> words;
cout << "Dati nr de cuvinte de ordonat:";
int n;
if (!(cin >> n)) throw runtime_error("bad input");
for (int i = 0; i < n; ++i) {
string word;
if (!(cin >> word)) throw runtime_error("bad input");
words.push_back(word);
}
cout << "Before sorting: " << words << "n";
sort(begin(words), end(words));
cout << "After sorting: " << words << "n";
}

最新更新