c++ - 当我在将文件读取到二维 c 字符串数组后尝试计算任何内容时出现 C++ 分段错误
问题描述
我正在为我的 cs124 课程做的一个 madLibs 项目的一部分涉及读取文件并将空格之间的每个单词/短语放入一个二维数组 ( fileArray
) 中,每一行包含一个不同的单词。问题是,在我读取文件后,我所做的每个 cout 语句都会Segmentation fault
出错。
我不允许使用字符串,所有内容都必须是 c-string 或 char [ ]。输入 .txt 文件的最大字符数限制为 256,文件中的每个单词的字符数限制为 32 个。我testfile.txt
用来测试我的代码;可能不相关,但文件只有文本:
This is a test file to test the fileArray function in MadLibs project
#include <iostream>
#include <fstream>
using namespace std;
#define WORD_CHAR_LIMIT 32
#define ARRAY_SIZE 256
void readFile(char fileArray[][WORD_CHAR_LIMIT]);
int main()
{
char fileArray[ARRAY_SIZE][WORD_CHAR_LIMIT];
cout << "this is a test\n";
readFile(fileArray);
cout << "this is a test\n";
return 0;
}
void readFile(char fileArray[][WORD_CHAR_LIMIT])
{
char fileName[ARRAY_SIZE];
cout << "Please enter the filename of the Mad Lib: ";
cin >> fileName;
ifstream fin(fileName);
if (fin.fail())
return;
char data;
int i = 0;
int j = 0;
fin >> data;
while (!fin.eof())
{
if (data != ' ')
fileArray[i][j] = data;
else if (data == ' ')
{
i++;
j = -1;
}
j++;
}
fin.close();
}
第一个 cout 按原样显示在屏幕上,但是在调用 之后,当我期望与第一个 cout 相同的东西时readFile()
,下一个 cout 会产生:Segmentation fault (core dumped)
[nbird11@LinuxLab02 ~]$ g++ project09.cpp
[nbird11@LinuxLab02 ~]$ a.out
this is a test
Please enter the filename of the Mad Lib: testfile.txt
Segmentation fault (core dumped)
解决方案
您可以将整个while
循环替换为:
while(fin >> fileArray[i]) ++i;
请注意,这while (!fin.eof())
不是一个好的测试。直到true
您实际尝试读取文件末尾之外的内容。
至于分段错误的原因,可能是您阅读data
一次并永远重复使用它:
fin >> data; // here you read data
while (!fin.eof()) // will never be true since you don't read more than once
{
// here you use data
if (data != ' ') // will always be true
else if (data == ' ') // will never be true
j++; // will just keep on going until you reach ARRAY_SIZE and then
// anything can happen. Undefined Behaviour.
}
因此,您将在循环的每次迭代中获得第一个字符,并且您很快就会越界。同样,替换while
循环中的条件会有所帮助:
while (fin >> data)
推荐阅读
- ruby - 返回哈希的默认值
- mysql - 如何在 mysql 中查询以选择整月的下午 4 点和晚上 10 点之间的时间
- javascript - React Link 组件在使用时会丢失 css 或 magin align
- ansible - 无法在 json_query ansible 模块中搜索字符串
- reactjs - ReactJS 鼠标事件在哪里解释?
- javascript - 如何使用 API 内部的 API URL 将对象添加到数组中?
- reverse-proxy - Traefik v2 作为没有 docker 的反向代理
- google-cloud-platform - 如何检查哪个用户停止了 GCP 中的数据流管道?
- macos - Samba 4.10 服务器配置:使用模块“vfs_fruit”更改 Mac 客户端的文件创建掩码,我无法控制它
- amazon-web-services - 来自 AWS 的 nginx 日志说“帮助...蝙蝠侠”?