将文本文件读取到2D数组中,但数组开始为超过数组[39][]的任何内容输出胡言乱语
Reading a text file into a 2D array, but array starts outputting gibberish for anything past array[39][ ]
我正在学习c++编程入门课程,我对标题问题有问题。我正在使用c型字符串将Haikus的文本文件(所有学生都提交了,我知道其中一半甚至不是合适的俳句(读取到2D数组中(这是作业的要求,所以我更希望答案集中在回复中使用c型串(。
当我输出存储在数组中的内容以确认所有内容都已正确复制时,就会出现问题。一旦它开始打印数组[I]中I>40的任何内容,它就会开始打印胡言乱语。
我把它缩小到第40行开始打印胡言乱语,第42行完全是胡言乱语。文件打开正确,我正在检查循环的每个实例的文件是否损坏。
//function for extracting text file into array
void getHaikus (ifstream& in, char haikuArray[][HAIKU_ARRAY_COL])
{
int i, j;
char str[50]; //ctype string variable
for(i=0;i<HAIKU_ARRAY_ROW && !in.eof();i++)
{
in.getline(str, 50); //read line into temp string
strncat(haikuArray[i], str, 50); //concatenate temp string into array
if(!in.good()) //check for file corruption during loop
{
cout << "file corrupt mid extractionn";
cout << "i value is: " << i << endl;
exit(1);
}
}
return;
}
预期输出:
To sit on blue *
Surronded, * birds rest,
* one last time.
.
.
.
Autumn is a *
And a very * one
* all the time
A candlelit *,
Cause * pumpkins to glow,
* October.
My * was with Nic
And they both like the *
* is awesome
实际输出:
To sit on blue *
Surronded, * birds rest,
* one last time.
.
.
.
Autumn is a *
And a very * one
* all the time
A candlelit *,
¼Cause * pumpkins to glow,
* October.
¾My nd they both like the *
o_Ò¾* is awesome
数组[40]以行"Cause*pumpkins…"开头
对任何格式不好的人深表歉意,这是我第一次把这个网站用作海报。感谢您提供的任何帮助!
为什么要使用strncat?将一个字符串附加到另一个字符串。看起来您想要的是strncpy,它复制一个字符串,而不需要用以null结尾的字符串初始化目标内存。–水稻
就是这样。从使用strncat转换为使用strncpy解决了这个问题。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '