我有一段代碼我在Cygwin的用C++運行我使用意外中止在C++
g++ -o program program.cpp
編譯和它返回讀取「中止(核心轉儲)」的誤差。它旨在通過命令行參數輸入文件名作爲輸入,計算文件中所有唯一字和全部單詞,並提示用戶輸入單詞並計算它們輸入的單詞的發生次數。它只打算使用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];
}
}
}
}
當您使用調試器時,哪個語句是中止前執行的最後一個語句?您在發佈之前確實使用了調試器,不是嗎? –
也許不相關,但請參閱http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – Barmar
我不確定你的意思;是否有一個內置於cygwin中的C++調試器?在我發佈之前,我一行一行地檢查代碼以檢查錯誤。 –