我总是在c字串的末尾得到一堆额外的字符

I keep getting a bunch of extra characters at the end of my C-String

本文关键字:一堆 字符      更新时间:2023-10-16

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

#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) != ''; x++)
        s++;
    return s;
}
void reset(char* arr, int size)
{
    for(int x = 0; x  < size; x++)
        *(arr + x) = '';
}
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)->wordtempcreateArr以便temp的有效内容可以复制到(cip + x)->word时,*(cip + x)->word总是在结束时产生大量的垃圾,尽管我将其中的所有内容设置为null并且只使用前一对索引。我该如何解决这个问题?

数据文件包含以下信息:

2311

Java 2 linux 3 fear 0 pool 2 do 0 red 1 lock1 .我0随机2台电脑,0不0开2台车!2 . C、0缺0狗1绿2 C++ 0瓶2错2他们。0

C风格字符串以空结束,因此最后一个可打印字符串后面的字符需要等于0或''。你可以在循环结束后手动设置,或者按照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;
    }