首页 > 解决方案 > 另一个版本的字符串列表,输出错误

问题描述

此代码应将 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;
}

标签: c++

解决方案


我无法编译/调试您的示例代码,因为它缺少Wordand的定义SList。但是根据你的调试结果,检测的字长是正确的,但内容是不正确的。所以问题需要在逻辑的某个地方*(s + i + j - (toAdd.length+1))

我的建议是尝试strncat。它将使您无法上下计算角色位置。

最后你应该得到类似的结果:

strncat(toAdd.letters, s + i - 1 - toAdd.length, toAdd.length);

推荐阅读