C+中的意外中止+; 我有一段代码在CygWin中运行C++,我用编译 g++ -o program program.cpp
并且它返回一个读取“中止(内核转储)”的错误。它旨在通过命令行参数将文件名作为输入,计算文件中的所有唯一单词和总单词数,并提示用户输入单词并计算他们输入的单词出现的次数。它只是打算用C++流来进行输入/输出。C+中的意外中止+; 我有一段代码在CygWin中运行C++,我用编译 g++ -o program program.cpp,c++,C++,并且它返回一个读取“中止(内核转储)”的错误。它旨在通过命令行参数将文件名作为输入,计算文件中的所有唯一单词和总单词数,并提示用户输入单词并计算他们输入的单词出现的次数。它只是打算用C++流来进行输入/输出。 #include <fstream> #include <iostream> #include <string> #include <cctype> using namespace std;
#include <fstream>
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main(int argc, char *argv[])
{
string filename;
for( int i = 1; i < argc; i++){
filename+=argv[i];
}
ifstream file;
file.open(filename.c_str());
if (!file)
{
std::cerr << "Error: Cannot open file" << filename << std::endl;
return 1;
}
string* words;
int* wordCount;
int wordLength = 0;
string curWord = "";
bool isWord;
int total = 0;
char curChar;
string input;
while(!file.eof())
{
file.get(curChar);
if (isalnum(curChar)) {
curWord+=tolower(curChar);
}
else if (!curWord.empty() && curChar==' ')
{
isWord = false;
for (int i = 0; i < wordLength; i++) {
if (words[i]==curWord) {
wordCount[i]++;
isWord = true;
total++;
}
}
if (!isWord) {
words[wordLength]=curWord;
wordLength++;
total++;
}
curWord="";
}
}
file.close();
// end
cout << "The number of words found in the file was " << total << endl;
cout << "The number of unique words found in the file was " << wordLength << endl;
cout << "Please enter a word: " << endl;
cin >> input;
while (input!="C^") {
for (int i = 0; i < wordLength; i++) {
if (words[i]==input) {
cout << wordCount[i];
}
}
}
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main(int argc,char*argv[])
{
字符串文件名;
对于(int i=1;i std::cerr您从未为要指向的单词和单词计数分配过任何空间。应该是:
#define MAXWORDS 1000
string *words = new string[MAXWORDS];
int *wordCount = new int[MAXWORDS];
然后在课程结束时,你应该做:
delete[] wordCount;
delete[] words;
或者,您可以分配一个本地阵列:
string words[MAXWORDS];
int wordCount[MAXWORDS];
但是您可以更简单地使用std::map
将字符串映射到一个计数。这将根据需要自动增长。当您使用调试器时,中止之前执行的最后一条语句是哪条语句?您在发布之前使用过调试器,不是吗?可能不相关,但我不确定您的意思;是否有调试器R为C++内置CygWin?在我发布之前,我逐行逐行检查代码。停止使用指针,<代码>单词< /Cord>和 WordCudio>代码>是未初始化的指针,并且通过它们读取/写入的每个地方都是一个错误。如果您想要一个动态数组,请使用“代码> STD::vector < /Calp>”或另一个标准库容器。yneExcalibur我不使用cygwin,但我敢打赌,gdb
是可用的,或者很容易安装。words
变量也有同样的问题。是的,刚刚添加了这个。谢谢;这真的很有帮助