我有一段代码我在Cygwin中用C ++运行我正在使用
进行编译g++ -o program program.cpp
它返回一个错误,上面写着'Aborted(core dumped)'。它旨在通过命令行参数获取文件名作为输入,计算文件中的所有唯一单词和总单词,并提示用户输入单词并计算他们输入的单词出现的次数。它只是用于输入/输出C ++流。
#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];
}
}
}
}
答案 0 :(得分:1)
您从未为words
和wordCount
分配任何空间来指向。它应该是:
#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
将字符串映射到计数来更简单地做到这一点。这将根据需要自动增长。