2011-05-06 4 views
1

편집을 cout을 넣어 : 부울 플래그로 변경,하지만 여전히 인쇄보다 더 그것을해야한다 :적절한 장소는

string line; // a string to hold the current line 
while(getline(myFile,line)) { 
bool old_count = false; // to help determine whether the line has been output yet 
for (unsigned int i = 0; i < line.length(); i++) { 
    string test = line.substr(i, targ_length); 
    if (strcmp(word.c_str(),test.c_str()) == 0 ) { 
     count++; 
     if (!old_count); { 
     cout << line_num << " : " << line << endl; 
     } // end if 
     old_count=true; 
    } // end if  
} //end for 
line_num++; 
} // end while 

/최종 편집

내가 검색하는 프로그램을 작성하는 과제를 가지고 텍스트 파일의 단어. 나는 단어가 발견 된 각 줄을 인쇄한다고 가정하고, 줄에 여러 번 나타나면 내 줄이 여러 번 인쇄 될 것입니다. 한 번만 줄을 인쇄해야합니다. 나는 다른 곳에서 if (count! = old_count)를 움직이는 것을 시도했지만 운이 좋지는 않으며 혼란 스럽다. 내 코드는 아래와 같습니다. 어떤 도움을 주셔서 감사합니다!

#include <iostream> 
#include <fstream> 
#include <string> 
#include <cstring> 
using namespace std; 

/* minimum required number of parameters */ 
#define MIN_REQUIRED 3 

/* display usage */ 
int help() { 
printf("Proper usage: findWord <word> <file>\n"); 
printf("where\n"); 
printf(" <word> is a sequence of non-whitespace characters\n"); 
printf(" <file> is the file in which to search for the word\n"); 
printf("example: findWord the test.txt\n"); 
return 1; 
} 

/* 
* Program that searches for occurrences of given word within a given file 
* @return 0 (default for a main method) 
*/ 
int main(int argc, char *argv[]) { 

if (argc < MIN_REQUIRED) { 
return help(); 
} // end if 

string word = argv[1]; // the word to be searched for 
string file_name = argv[2]; // the name of the file to be read 

ifstream myFile(file_name.c_str()); // read the file 
if (! myFile) { 
cerr << "File '" << file_name << "' could not be opened" << endl; 
return -1; 
} // end if 

cout << "Searching for '" << word << "' in file '" << file_name << "'\n"; 

int targ_length = word.length(); // the legnth of the string we're searching for 

int count = 0; // running count of instances of word found 
int line_num = 1; // number of current line 

string line; // a string to hold the current line 
while(getline(myFile,line)) { 
int old_count = count; // to help determine whether the line has been output yet 
for (unsigned int i = 0; i < line.length(); i++) { 
    string test = line.substr(i, targ_length); 
    if (strcmp(word.c_str(),test.c_str()) == 0 ) { 
     count++; 
    } // end if 
    if (old_count != count); { 
     cout << line_num << " : " << line << endl; 
    } // end if  
} //end for 
line_num++; 
} // end while 

cout << "# occurrences of '" << word <<" ' = " << count << endl; 

return 0; 
} 

답변

1

다음처럼 bool 플래그에 대한 int 플래그를 변경해보십시오 : 당신은 작업에 대한 잘못된 도구를 사용하는

while(getline(myFile,line)) { 
bool old_count = false; // to help determine whether the line has been output yet 
bool second_flag = false; 
for (unsigned int i = 0; i < line.length(); i++) { 
    string test = line.substr(i, targ_length); 
    if (strcmp(word.c_str(),test.c_str()) == 0 ) { 
     old_count = true; 
    } // end if 
    if (old_count && !second_flag){ 
     cout << line_num << " : " << line << endl; 
     second_flag = true; 
    } // end if  
} //end for 
line_num++; 
} // end while 
+0

부울 플래그가 좋은 생각 :

코드는 다음과 같은 것! 나는 둥지를 내가 생각했던 것으로 바 꾸었습니다. 그러나 단어가 두 번 이상 발견되면 그것은 여전히 ​​여러 줄을 인쇄합니다. 이전 줄을 읽을 때까지 old_count를 다시 false로 설정하면 안됩니다. 내가 뭘 놓치고 있니? (편집보기) –

+0

코드를 제공 한 방식에 따라 플래그는 모든 라인에 대해 한 번만'false'로 설정됩니다. 편집 : 내 편집 된 스 니펫을 확인하십시오. 플래그가 올바르게 설정되지 못하게하는'; '이 있는지 확실하지 않습니다. – camiloqp

+0

당신이 지정한대로 시도 했으므로 프로그램은 테스트하는 모든 하위 문자열에 대해 현재 행을 인쇄합니다. 어느 쪽을해서는 안되는가. ? –

-1

. 현재 줄의 각 문자에 대해 substr()을 호출하는 대신 줄 내에서 원하는 문자열을 찾는 함수를 사용하십시오. strstr()과 같은 것처럼 보일 수도 있습니다. http://www.cplusplus.com/reference/clibrary/cstring/strstr/

+0

'strstr()'은 C 문자열에서 작동하며 OP는 분명히 사용하지 않습니다. 'find()'를 추천 할 수있다. – Puppy

+0

예 감사하지만 우리는 strcmp()를 사용하라는 지시를 받았습니다. 그리고 그 작품; 문제는 현재 행을 출력하는 횟수입니다. –

+0

strcmp() 사용이 필요하다는 정보를 기반으로 또 다른 대답을 제공했습니다. – Alanyst

1

std::set과 같은 연관성 컨테이너는 반복적으로 삽입하려고 시도해도 한 번만 줄 값을 보유합니다.

또한 코드에는 매우 무의미한 C-isms가 가득합니다.

if (strcmp(word.c_str(),test.c_str()) == 0 ) { 

if (word == test)) { 

#definestatic const int되어야 있어야 printfcout 대체.

+0

우리는 strcmp를 사용하라고 들었지만, 다른 무의미한 C-isms에 대한 조언에 감사드립니다 ... 그것들을 고쳤습니다 ... 저는 여전히 n00bish입니다. –

1

단어가있는 경우 한 번 줄을 인쇄해야하는 경우 줄에 추가 단어가 몇 번 추가 되더라도 첫 번째 항목을 찾은 후에 계속 검색 할 이유가 없습니다. 처음에 줄에 단어를 찾으면 줄 번호와 줄을 즉시 인쇄 한 다음 inner for 루프에서 빠져 나오십시오. 이렇게하면 개수 변수를 신경 쓰지 않아도됩니다.

while(getline(myFile,line)) { 
    for (unsigned int i = 0; i < line.length(); i++) { 
     string test = line.substr(i, targ_length); 
     if (strcmp(word.c_str(),test.c_str()) == 0 ) { 
      cout << line_num << " : " << line << endl; 
      break; // exit inner for loop as soon as the word is found 
     } // end if  
    } //end for 
    line_num++; 
} // end while 
+0

감사합니다. 그게 파일을 다 끝나면 얼마나 많은 인스턴스를 찾았는지 출력하기 위해 count 변수가 필요하다는 것 외에는 작동 할 것이다. 알았어. –

관련 문제