我在C-String末尾不断收到一堆额外的字符

时间:2016-10-12 06:29:38

标签: c++ arrays pointers dynamic

我正在完成学校作业,我必须从文件中读取动态分配的结构数组。我只能为所有数组使用C Style字符串和指针数组语法(即 *(pointer + x))。我已经到了一个点,我试图将所有内容加载到他们的位置,但是当我这样做时,我的单词变量的末尾总是有垃圾。如何解决这个问题?

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

struct Pieces
{
    char* word;
    int jump;
};

void reset(char*, int);
int strLen(char*);
void createArr(char*, char*);

int main()
{
    Pieces* cip;
    char* temp;
    ifstream input;
    int numWords, numKeys;

    temp = new char[20];
    input.open("Project4Data.txt");
    input >> numWords;
    input >> numKeys;
    cip = new Pieces[numWords];
    for(int x = 0; x < numWords; x++)
    {
        int tempSize;
        reset(temp, 20);
        input >> temp;
        tempSize = strLen(temp);
        //cout << temp << " ";
        (cip + x)->word = new char[tempSize];
        //cout << tempSize;
        reset((cip + x)->word, tempSize);
        createArr((cip + x)->word, temp);
        input >> (cip + x)->jump;
        //cout << (cip + x)->word<<  << endl;
    }
    input.close();

    //cout << (cip + 2)->word;
    delete[] cip;
    return 0;
}

int strLen(char* word)
{
    int s = 0;
    //cout << word;
    for(int x = 0; *(word + x) != '\0'; x++)
        s++;
    return s;
}

void reset(char* arr, int size)
{
    for(int x = 0; x  < size; x++)
        *(arr + x) = '\0';
}

void createArr(char* a, char* b)
{
    reset(a, strLen(b));
    for(int x = 0; x < strLen(b); x++)
        *(a + x) = *(b + x);
        cout << a;
}

当我将 (cip + x) - &gt;字 temp 发送到 createArr 时以便 temp 的有效内容可以复制到 (cip + x) - &gt; word * (cip + x) - &gt; word 最后总会出现大量垃圾,尽管我将其中的所有内容设置为null并且只使用前几个索引。我该如何解决这个问题?

数据文件上有这个信息:

23 11

Java 2 linux 3恐惧0池2做0红1锁。 1我0随机2台电脑,0不0 0开2车! 2 C,0缺少0 0狗1绿2 C ++ 0瓶2错2,它们。 0

1 个答案:

答案 0 :(得分:0)

C样式字符串以空值终止,因此最终可打印字符之后的字符需要等于0,或者&#39; \ 0&#39;。 你可以在循环之后手动设置它,或者按照Adrian的说法进行设置,并用小于等于的值替换小于。

void createArr(char* a, char* b)
{
    reset(a, strLen(b));
    for(int x = 0; x < strLen(b); x++)
        *(a + x) = *(b + x);
        *(a + x) = *(b + x);
        cout << a;
}

或(可能更整洁)

  void createArr(char* a, char* b)
    {
        reset(a, strLen(b));
        for(int x = 0; x <= strLen(b); x++)
            *(a + x) = *(b + x);
            cout << a;
    }
相关问题