C++ 输出错误的字符串列表的另一个版本
这段代码应该将char*转换为我自己的struct SList,它只是前一个数组中的一个单词列表(用空格分隔),然后创建一个ostream我无法编译/调试示例代码,因为它缺少C++ 输出错误的字符串列表的另一个版本,c++,C++,这段代码应该将char*转换为我自己的struct SList,它只是前一个数组中的一个单词列表(用空格分隔),然后创建一个ostream我无法编译/调试示例代码,因为它缺少Word和SList的定义。但是根据您的调试结果,单词长度的检测是正确的,而不是内容。因此问题需要在*(s+i+j-(toAdd.length+1))的逻辑中的某个地方 我的建议是试试看。它可以防止你上下计算角色的位置 最后,您应该得到如下结果: strncat(toAdd.letters,s+i-1-toAdd.lengt
Word
和SList
的定义。但是根据您的调试结果,单词长度的检测是正确的,而不是内容。因此问题需要在*(s+i+j-(toAdd.length+1))
的逻辑中的某个地方
我的建议是试试看。它可以防止你上下计算角色的位置
最后,您应该得到如下结果:
strncat(toAdd.letters,s+i-1-toAdd.length,toAdd.length);
请确保发布您的定义(我没有看到SList
定义的任何地方)。事实上,这段代码。您正在显示的输出必须来自未在此处显示的代码。请回答您的问题以修复此疏忽。您缺少一个main()函数,其中有一个示例说明如何使用此函数。*(toAdd.letters+j)
调用未定义的行为-您尚未初始化指针toAdd.letters
@谢谢,成功了,您保存了我的分数!
fu
fuc
fuc
fucy
#include <iostream>
using namespace std;
int n = 16;
char * input = new char [16] {'n', 'o', ' ', 'w', 'a', 'y', ' ', 't', 'h', 'e', ' ', 'f', 'u', 'c', 'y', '\0'};
struct Word{
char * letters;
int length;
};
struct SList {
Word * wordList;
int length;
};
int listSize(char * s, int n){
int result = 0;
for(int i = 0; i < n; i++){
if(*(s + i) == ' ') result++;
}
return result + 1;
}
SList createList(char * s, int n){
int _listSize = listSize(s, n);
SList myList;
myList.length = _listSize;
myList.wordList = new Word [myList.length];
int k = 0;
for(int i = 0; i < n; i++){
int counter = 0;
char symbol = *(s + i);
Word toAdd;
while(symbol != ' '){
symbol = *(s + i);
if(i == n) break;
counter++;
i++;
}
toAdd.length = counter - 1;
for(int j = 0; j < toAdd.length; j++){
*(toAdd.letters + j) = *(s + i + j - (toAdd.length+1));
}
*(myList.wordList + k) = toAdd;
k++;
i--;
}
return myList;
}
ostream &operator<<(ostream &os, SList &myList) {
for (int i = 0; i < myList.length; i++) {
for(int j = 0; j < myList.wordList[i].length; j++){
os << myList.wordList[i].letters[j];
}
os << endl;
}
return os;
}
int main(){
SList myList = createList(input, n);
cout << myList;
}