【发布时间】:2017-10-08 16:13:44
【问题描述】:
大家早上好,
我正在为学校编写一个简单的程序,它从 .txt 文件中读取行并将每个字符的数量输出到一个新文件中。我已经被困了几个小时,因为我无法弄清楚分段错误发生在哪里。当我在 Visual Studio 中编译和调试时不会发生这种情况,但是当我在学校的服务器上编译并运行我的程序时会出现。我知道除了分段错误之外程序中仍然存在缺陷,但我更愿意自己解决这些问题:)。提前感谢您的帮助。
主要:
#include <iostream>
#include <fstream>
#include <string>
#include "letterFunctions.hpp"
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::iostream;
using std::ifstream;
using std::ofstream;
using std::ios;
void count_letters(ifstream &ifs, int* freqArray);
int main()
{
//Declare the string for the input file and create the input stream.
ifstream ifs;
string inputFileName;
//Initialize the array for the frequency of each letter.
int *freqArray = new int[26];
//Prompt the user for the input file name.
cout << "Enter the name of the file to be analyzed." << endl;
cin >> inputFileName;
//Open the file.
ifs.open(inputFileName.c_str());
//If the file doesn't exist, prompt the user for a new file.
while (ifs.fail())
{
cout << "Invalid entry. Enter the name of the file to be analyzed." << endl;
cin >> inputFileName;
ifs.open(inputFileName.c_str());
}
count_letters(ifs, freqArray);
//Close the input file.
ifs.close();
return 0;
}
letterFunctions.cpp:
#include <fstream>
#include <iostream>
#include <string>
#include "letterFunctions.hpp"
using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::string;
ofstream ofs;
void count_letters(ifstream &ifs, int* freqArray)
{
//Initialize new variables.
int arrayModifier = 0;
char input;
//Read the first character of the file.
input = ifs.get();
while (input != EOF)
{
//Reset the array to 0's.
for (int i = 0; i < 26; i++)
{
freqArray[i] = 0;
}
while (input != '\n')
{
//Convert all chars to upper case.
if ((int)input >= 97 && (int)input <= 122)
{
putchar(toupper(input));
}
//Set the array modifier to the corresponding letter, and add one to the counter.
arrayModifier = ((int)input - 65);
freqArray[arrayModifier]++;
//Get the next character.
input = ifs.get();
}
//Output to the file.
output_letters(ofs, freqArray);
input = ifs.get();
}
}
void output_letters(ofstream &ofs, int* freqArray)
{
string outputFileName;
cout << "Enter the name of the file you would like to output this paragraph to." << endl;
cin >> outputFileName;
ofs.open(outputFileName.c_str());
int l = 65;
for (int i = 0; i < 26; i++)
{
ofs << (char)l << ": " << freqArray[i] << "\n";
l++;
}
ofs.close();
}
【问题讨论】:
-
请edit您的问题提供minimal reproducible example。
-
arrayModifier = ((int)input - 65); freqArray[arrayModifier]++;很容易导致缓冲区溢出 -
只要
input字符不在A和Z之间,您的程序就会访问越界的索引。 -
与您的问题无关,但请尽量避免magic numbers。例如,如果您通过值
65表示'A'的ASCII 表示,那么最好使用'A'。在相关说明中,您的代码仅适用于 ASCII 和类似的字符编码方案,其中字母是连续的。有些编码不正确(例如EBCDIC)。
标签: c++ visual-studio