我正在做一项学校作业,其中我必须从一个文件中读取到一个动态分配的结构数组中。对于所有数组,我只能使用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) != '\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)->word和temp发送到createArr以便temp的有效内容可以复制到(cip +x)->wordE 214、E 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
发布于 2016-10-12 06:36:35
C样式字符串为null,因此最终可打印字符串后面的字符需要等于0或'\0‘。您可以在循环之后手动设置这个值,或者按照禤浩焯的话做,然后用小于/等于替换小于/等于。
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;
}https://stackoverflow.com/questions/39991868
复制相似问题