c++ - 另一个版本的字符串列表,输出错误
问题描述
此代码应将 char* 转换为我自己的结构 SList,它只是前一个数组中的单词列表(用空格分隔),然后为其创建一个 ostream << 运算符
但这是输出:
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;
}
解决方案
我无法编译/调试您的示例代码,因为它缺少Word
and的定义SList
。但是根据你的调试结果,检测的字长是正确的,但内容是不正确的。所以问题需要在逻辑的某个地方*(s + i + j - (toAdd.length+1))
。
我的建议是尝试strncat。它将使您无法上下计算角色位置。
最后你应该得到类似的结果:
strncat(toAdd.letters, s + i - 1 - toAdd.length, toAdd.length);
推荐阅读
- javascript - 在 Botframework WebChat 上同时显示麦克风和发送按钮
- android-studio - Ionic Bundle ID 更改后仍会导致问题
- json - 无法从 grails 中具有复合键的域类中获取其余 API
- jsonschema - 如何根据属性存在更改 json 模式?
- c - 在运行时为枚举添加后缀
- angular - Ionic 3如何检测元素是否在滚动视图中
- javascript - 计算有或没有间隔的总日期范围
- arrays - 无法使用类型为“([TT])”的参数列表调用“附加”
- javascript - 我可以手动更改吗DOM与本机JS的实际可显示颜色?
- kubernetes - 在普罗米修斯中找不到 APIServiceRegistrationController 指标