我总是在c字串的末尾得到一堆额外的字符
I keep getting a bunch of extra characters at the end of my C-String
我正在做一项学校作业,其中我必须从文件中读取到动态分配的结构数组。我只能使用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)->word和temp到createArr以便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;
}
相关文章:
- 如何使用结构和指针推动和弹出一堆双打
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 用最少的代码行数替换c++中的一组字符
- 当我在结构中包含多个数组时,我的程序会跳过一堆代码
- 匹配匹配任何内容,直到'%'不后跟'%',后跟一组字符
- 在共享指针的值中调用 std::swap 调用一堆构造函数和析构函数
- 至少包含一次字符 X 的 S 的不同子字符串的数量
- 给定一组字符和长度的排列
- 使用带有.lib和一堆.dll和.h文件的Python CFFI
- 用 c++ 编写一堆类似的 if 语句的漂亮方法
- 当我尝试编译程序时,我遇到了一堆错误,例如:'std::max':找不到匹配的重载函数
- Swig C++ to python:编译一堆.cpp和.h文件
- template元编程:将一堆模板参数相乘
- 为什么弦乐在代表时不会移至下一组字符
- 在.NET中存储一堆恒定值的最佳方法
- 我的一堆函数出现"undefined reference"错误,我不知道为什么
- C++将字符从静态数组复制到动态数组会添加一堆随机元素
- 我总是在c字串的末尾得到一堆额外的字符
- 当我试图在c++中反转cstring时,我得到了一堆额外的字符
- write(2)在我写完文件后写了一堆垃圾字符