C++缓冲区太小错误

C++ Buffer is too small Error

本文关键字:错误 缓冲区 C++      更新时间:2023-10-16

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

引发的异常是:

调试断言失败!

File: minkernel\crts\ucrt\corecrt_internal_string_templates.h

行: 81

表达式:(L"缓冲区太小" &&&0)

该函数从列出了一周中的 7 天(周一至周日)的 .txt 文件中读取,然后按字母顺序对 2D 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 
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 样式字符串执行冒泡排序,但您的冒泡排序实现不正确。请参阅此页面,了解如何实现简单的气泡排序。提示: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])时,这意味着你想打印出整个字符串,直到 null 终止符。

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


当我吹毛求疵时

尽量不要使用using namespace::std;,有很多理由说明你不应该这样做。