C++ 缓冲区太小错误

C++ Buffer is too small Error

间歇性地,Visual Studio 在 运行 运行我的代码时抛出异常。我断断续续地说是因为我已经能够成功 运行 我的代码而没有错误。在我创建函数“print_Days”后抛出错误。“

抛出的异常是:

Debug Assertion Failed!

File: minkernel\crts\ucrt\corecrt_internal_string_templates.h

Line: 81

Expression: (L"Buffer is too small" && 0)

该函数从列出一周中的 7 天(周一至周日)的 .txt 文件中读取,然后按字母顺序对二维 c 字符串数组中的日期进行排序(教授让我们使用 c 字符串而不是不幸的是字符串)。

这是我的全部代码:

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>

using namespace std;
//Constants for 2D array
const int NUM_OF_ROWS = 7; //Seven days listed in the file
const int NUM_OF_COLS = 10; //Longest word is 9 chars long, plus [=10=]

void get_Days(ifstream& file, char days[][NUM_OF_COLS], int rows);
void sort_Days(char days[][NUM_OF_COLS], int rows);
void print_Days(const char days[][NUM_OF_COLS], const int rows);

void get_Days(ifstream& file, char days[][NUM_OF_COLS], int rows) {
   //Read from text file and return day
   for (int i = 0; i < rows; ++i)
   {
      file >> days[i];
   }
}

void sort_Days(char days[][NUM_OF_COLS], int rows) {
   //Sort the array alphabetically
   char temp[NUM_OF_COLS];
   for (int i = 0; i < rows; i++)
   {
      for (int j = 0; j < rows; j++)
      {
         if (strcmp(days[j - 1], days[j]) > 0)
         {
            strcpy_s(temp, days[j - 1]);
            strcpy_s(days[j - 1], days[j]);
            strcpy_s(days[j], temp);
         }
      }
   }
}

void print_Days(const char days[][NUM_OF_COLS], const int rows) {
   //Print the sorted array to the console
   for (int i = 0; i < NUM_OF_ROWS; ++i)
      for (int i = 0; i < rows; i++)
      {
         for (int j = 0; j < NUM_OF_COLS; j++)
         {
            cout << days[i][j] << endl;
         }
      }
}

int main() {
   //This program reads from a file (days.txt), sorts the days 
   // alphabetically, and then prints the result to the console.
   ifstream infile("days.txt");
   char days[NUM_OF_ROWS][NUM_OF_COLS];
   if (!infile)
   {
      cout << "File (days.txt) does not exist." << endl;
      return 1;
   }
   get_Days(infile, days, NUM_OF_ROWS);
   infile.close();
   sort_Days(days, NUM_OF_ROWS);
   print_Days(days, NUM_OF_ROWS);
   return 0;
}

代码有几处错误:

sort_Days

sort_Days 算法抛出错误,因为当嵌套的 for 循环以 j = 0 开始时,您正试图索引 days[j - 1]。所以你的初始索引是越界的。

此外,您似乎正尝试对 C 风格的字符串执行冒泡排序,但您的冒泡排序实现不正确。请参考 this page 了解如何实现简单的冒泡排序。提示:for 循环条件,strcmpstrcpy_s 索引需要一些调整。


print_Days

您的 print_Days 函数不正确。这是一个打印出每个 c 风格字符串而不是字符串中每个 char 的版本:

void print_Days(const char days[][NUM_OF_COLS], const int rows) 
{
    for (int j = 0; j < rows; j++)
    {
        cout << days[j] << endl;
    }
}

你应该知道 std::cout 理解当你传递给它一个 c 风格的字符串时(即 days 中的 char[NUM_OF_COLS]),这意味着你想要打印出整个字符串直到空终止符。

你的for循环终止条件也是错误的,因为你有j < NUM_OF_COLS,而days实际上是一个有NUM_OF_ROWS个元素的数组,每个元素都是一个NUM_OF_COLS 大小的数组。你的方式索引超出了 days 数组的范围。


趁我吹毛求疵

尽量不要使用using namespace::std;there are plenty of reasons why you shouldn't.