2013-06-13 2 views
3

벡터 내부의 단어 수를 계산하는 데 문제가 있습니다. 벡터는 파일의 모든 행을 객체로 유지합니다. 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; 
} 

답변

6

RichieHindle의 답변에 대한 대안으로이 방법도 있습니다. for 루프에 대해 stringstream 범위를 지정하면 올바르게 재설정됩니다.

int countWords(vector<string> v) 
{ 
    string word; 
    int count = 0; 
    for(int i = 0; i < v.size(); i++) { 
     stringstream ss(v[i]); 
      while (ss >> word) 
       count++; 
    } 
    return count; 
} 
+0

매우 도움이됩니다. 정말 고마워요. –

1

나는 ss가 처음으로 배출 한 당신이 str를 호출해서 초기화되지 않을 때 오류 상태로 전환 내기.

for 루프 내에 ss을 선언하고 문자열을 생성자에 직접 전달하십시오. 이렇게하면 이러한 문제를 피할 수 있습니다.

일반적으로 변수를 필요로하는 곳과 가장 가깝고 묶음으로 선언하는 습관이 있습니다. 생성자를 사용하지 않는 것이 좋습니다. 예를 들어 open을 호출하는 대신 fstream의 생성자에 파일 이름을 전달할 수 있습니다. 그리고 ifstream을 사용할 수 있으므로 두 번째 인수가 필요하지 않습니다. 당신은 이제 stringstream을 다시 사용하기 전에

4

당신은 당신의 while 루프 후

ss.clear(); 

을 수행해야합니다.

for() 루프 내에서 선언 할 수도 있지만 다시 초기화 할 수 있습니다. readabillity 들어,이 더 좋을 수도 있습니다. Performancewise 그것은 차이를 만들 수 있습니다.

+1

알아두면 좋습니다. ss.str (string())을 사용하여 이전에 시도하려고했지만 clear()가 더 합리적인 방법입니다. –

관련 문제