벡터 내부의 단어 수를 계산하는 데 문제가 있습니다. 벡터는 파일의 모든 행을 객체로 유지합니다. v [0]은 첫 x 째 행이고, v [1]은 두 x 째 행입니다.C++ : 계산 기능이 첫 번째 줄만 카운트합니다.
내 countWords() 함수의 경우 v [0]의 계산에만 사용됩니다. 그 이후의 모든 객체는 무시되거나 일부 방법을 놓쳤습니다. 어떤 아이디어? 미리 감사드립니다.
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int countWords(vector<string> v)
{
stringstream ss;
string word;
int count = 0;
for(int i = 0; i < v.size(); i++) {
ss.str(v[i]);
while (ss >> word)
count++;
}
return count;
}
void readFile(string filename,vector<string> &v)
{
fstream file;
string line;
file.open(filename,ios::in);
while(getline(file,line)) { //Reads the file line by line ...
if(line == "") //... ignoring any empty lines ...
continue;
v.push_back(line); //... and puts them into our vector.
}
file.close();
}
int main(int argc,char* argv[])
{
if (argc != 2) { //Terminate unless the user enters -ONE- entry.
cout << "Usage: " << argv[0] << " <filename>" << endl;
exit(1);
}
string filename = argv[1];
vector<string> fileContents;
readFile(filename,fileContents);
cout << countWords(fileContents) << endl;
}
매우 도움이됩니다. 정말 고마워요. –