편집을 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;
}
부울 플래그가 좋은 생각 :
코드는 다음과 같은 것! 나는 둥지를 내가 생각했던 것으로 바 꾸었습니다. 그러나 단어가 두 번 이상 발견되면 그것은 여전히 여러 줄을 인쇄합니다. 이전 줄을 읽을 때까지 old_count를 다시 false로 설정하면 안됩니다. 내가 뭘 놓치고 있니? (편집보기) –
코드를 제공 한 방식에 따라 플래그는 모든 라인에 대해 한 번만'false'로 설정됩니다. 편집 : 내 편집 된 스 니펫을 확인하십시오. 플래그가 올바르게 설정되지 못하게하는'; '이 있는지 확실하지 않습니다. – camiloqp
당신이 지정한대로 시도 했으므로 프로그램은 테스트하는 모든 하위 문자열에 대해 현재 행을 인쇄합니다. 어느 쪽을해서는 안되는가. ? –