因此,我必须将一个 char* 转换为我自己的结构 SList,它只是前一个数组中的单词列表(用空格分隔),然后为其创建一个 ostream << 运算符
但这里是输出:
8° └
8°
8° └
8
怎么了? 此外,所有输出元素似乎都相同,只是长度不同
#include <iostream>
using namespace std;
struct Word {
int size;
char *symbols;
};
struct SList {
int size;
Word *myArray;
};
SList third(char *words, int size, size_t n) {
int indexOfMyArray = 0;
int index = 0;
Word *myArray = new Word[size];
for (int i = 0; i < size; i++) {
char *word = new char[n];
int k = 0;
while (words[index] >= 'a' && words[index] <= 'z') {
word[k] = words[index];
k++;
index++;
}
word[k] = '\0';
index++;
Word word1 = {k, word};
myArray[indexOfMyArray] = word1;
indexOfMyArray++;
cout << word << ' ';
for (int k = 0; k < word1.size; k++)
cout << word1.symbols[k];
cout << endl;
delete[](word);
}
cout << endl;
SList list = {size, myArray};
return list;
}
ostream &operator<<(ostream &os, const SList &list) {
for (int i = 0; i < list.size; i++) {
for (int j = 0; j < list.myArray[i].size; j++) {
os << static_cast<char>(list.myArray[i].symbols[j]+0);
}
os << endl;
}
return os;
}
int main() {
char chars[19] = {'e', 'z', 'e', 's', 'c', ' ', 'e', 'f', 't', ' ', 'y', 'y', 'y', 'y', 'y', 'y', ' ', 'f', 'h'};
SList list = third(chars, 4, 19);
cout << list << endl;
system("pause");
}
最佳答案
如评论中所示,使用 C++ 类型可以使问题更易读和理解。
#include <iostream>
using namespace std;
using Word = std:: string;
using SList = std::vector<Word>;
SList third(std::string const &words) {
SList myArray;
int index = 0;
while (index < words.size()) {
Word word;
while (words[index] >= 'a' && words[index] <= 'z') {
word += words[index];
index++;
}
myArray.push_back( word);
cout << word << ' ' << myArray.back() << std::endl;
}
cout << endl;
return myArray;
}
// I believe this operator is actually undefined behavior as you ain't allowed to write this method for standard types.
ostream &operator<<(ostream &os, const SList &list)
{
for (auto &&word : list)
os << word << std::endl;
return os;
}
int main() {
std::string chars {"ezesc eft yyyyyy fh"};
SList list = third(chars);
cout << list << endl;
system("pause");
}
以上解决了您的问题,因为内存管理突然对您隐藏了。这是好事!
在您的代码中:问题在于:delete[](word);
word 的内存仍然由您存储的指针引用。因此,当访问该内存时,您有未定义的行为并且结果不是很好。你很不幸它没有崩溃。
关于c++ - 我的结构是一个单词列表,必须在之后输出。但是输出格式不对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53659732/