首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我一直在我的C-字符串末尾得到一堆额外的字符

我一直在我的C-字符串末尾得到一堆额外的字符
EN

Stack Overflow用户
提问于 2016-10-12 06:29:37
回答 1查看 295关注 0票数 0

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

代码语言:javascript
运行
复制
#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)->wordtemp发送到createArr以便temp的有效内容可以复制到(cip +x)->wordE 214E 115*(cip+x)->wordE 216时,最后总是会出现大量垃圾,尽管我将其中的所有内容都列出为null,并且只使用第一对索引。我该怎么解决这个问题?

数据文件包含以下信息:

23 11

Java 2 linux 3害怕0池2做0红色1锁。1 i 0随机2台电脑,0不0的0开2辆车!2 C,0缺少0的0狗1绿色2 C++ 0瓶2错,2他们。0

EN

回答 1

Stack Overflow用户

发布于 2016-10-12 06:36:35

C样式字符串为null,因此最终可打印字符串后面的字符需要等于0或'\0‘。您可以在循环之后手动设置这个值,或者按照禤浩焯的话做,然后用小于/等于替换小于/等于。

代码语言:javascript
运行
复制
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;
}

或者(可能更整洁)

代码语言:javascript
运行
复制
  void createArr(char* a, char* b)
    {
        reset(a, strLen(b));
        for(int x = 0; x <= strLen(b); x++)
            *(a + x) = *(b + x);
            cout << a;
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39991868

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档