首页 > 解决方案 > 当我在将文件读取到二维 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)

标签: c++file

解决方案


您可以将整个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)

推荐阅读