将文本文件读取到2D数组中,但数组开始为超过数组[39][]的任何内容输出胡言乱语

Reading a text file into a 2D array, but array starts outputting gibberish for anything past array[39][ ]

本文关键字:数组 胡言乱语 输出 任何内 开始 读取 文件 文本 2D      更新时间:2023-10-16

我正在学习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解决了这个问题。