我正在尝试计算来自用户的文本文件中的单词数,将它们写入向量,然后输出一个文本文件,其中第一行的单词数和后续行由向量中的单词组成,显示按排序顺序。有什么想法有什么问题吗?
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
#include <stdio.h>
#include <ctype.h>
using namespace std;
//gets user input for file names to open/write to
string getUserInput (string inputORoutput) {
cout << "Enter desired " << inputORoutput << " filename (include file extension). ";
string userInput;
getline(cin,userInput);
return userInput;
}
//ensures that string word is an alphabetical word
string isAlpha (string& word) {
string newWord;
for (int i = 0; i < word.length(); i++) {
if (isalpha(word[i])) {
newWord += word[i];
}
else if (isspace(word[i])) {
word[i] = word[i+1];
}
else {
newWord = "";
}
}
return newWord;
}
//removes empty elements of uniqueWords
void removeEmptyLines (vector<string>& uniqueWords) {
for (int i = 0; i < uniqueWords.size(); i++) {
if (uniqueWords [i] == "") {
uniqueWords.erase(uniqueWords.begin() + i);
}
}
}
//calls isAlpha, calls removeEmptyLines, & sorts uniqueWords in alphabetical order
void sortUniqueWords (vector<string>& uniqueWords) {
sort (uniqueWords.begin(), uniqueWords.end());
for (int i = 0; i <= uniqueWords.size(); i++) { //remove this loop if digits are allowed
uniqueWords[i] = isAlpha(uniqueWords[i]);
}
removeEmptyLines(uniqueWords); //remove this loop if digits are allowed
if (uniqueWords.size() == 2) { //alpha.txt wont work without this
uniqueWords [1] = "";
}
}
//adds a new unique word to uniqueWords vector
void addUniqueWord (vector<string>& uniqueWords, string lineToAdd) {
bool doesContain = false;
int i = 0;
while (i <= uniqueWords.size() && !doesContain) {
if (lineToAdd == uniqueWords [i]) {
doesContain = true;
}
else {
i++;
}
}
if (!doesContain) {
uniqueWords.push_back(lineToAdd);
}
}
int main(int argc, const char * argv[]) {
vector<string> uniqueWords(1); //for some reason the program produces error EXC_BAD_ACCESS (code=1, address=0x0)
string fileName;
ifstream inFile;
inFile.open(getUserInput("input"));
string currentLine = "";
while (getline(inFile, currentLine)) { //reads input and tests for failure
addUniqueWord (uniqueWords, currentLine);
}
uniqueWords.erase(uniqueWords.begin() + 1);
uniqueWords.erase(uniqueWords.begin());
sortUniqueWords (uniqueWords);
inFile.close();
ofstream outFile;
outFile.open(getUserInput("output"));
for (int i = 0; i <= uniqueWords.size(); i++) {
outFile << uniqueWords[i] << endl;
}
return 0;
}