我試圖從一個文件中讀取,並從文件中創建一個所有單詞的向量。我在下面嘗試做的是讓用戶輸入文件名,然後讓代碼打開文件,如果它們不是字母數字,則跳過字符,然後將其輸入到文件中。試圖讀取文件並跳過C++中的標點符號?
現在它只是當我輸入文件名時立即關閉。任何想法我可能做錯了什麼?
#include <vector>
#include <string>
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
string line; //for storing words
vector<string> words; //unspecified size vector
string whichbook;
cout << "Welcome to the book analysis program. Please input the filename of the book you would like to analyze: ";
cin >> whichbook;
cout << endl;
ifstream bookread;
//could be issue
//ofstream bookoutput("results.txt");
bookread.open(whichbook.c_str());
//assert(!bookread.fail());
if(bookread.is_open()){
while(bookread.good()){
getline(bookread, line);
cout << line;
while(isalnum(bookread)){
words.push_back(bookread);
}
}
}
cout << words[];
}
此代碼不被編譯:'words'是一個'的std ::矢量'所以'字[]'丟失的參數。 (根據[此鏈接](http://www.cplusplus.com/reference/stl/vector/operator [] /),沒有不帶參數的過載) –
ereOn
2011-02-28 23:08:23
+1 to ereOn。你會想要遍歷矢量'單詞'中的每個項目並輸出到'cout'。 – arviman 2011-02-28 23:11:45
當這行'getline(bookread,line);'失敗時會發生什麼?你不檢查失敗。 – 2011-02-28 23:22:34