[c++] 조건문을 이용한 효과적인 데이터 검색
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string keyword = "apple";
std::string line;
std::ifstream file("data.txt");
if (file.is_open()) {
while (std::getline(file, line)) {
if (line.find(keyword) != std::string::npos) {
std::cout << "Keyword found in file: " << line << std::endl;
}
}
file.close();
} else {
std::cout << "Unable to open file";
}
return 0;
}
위 코드는 “data.txt” 파일에서 “apple”이라는 키워드를 검색하여 해당 라인을 출력하는 예제입니다. 해당 코드는 ifstream와 string 라이브러리로 txt 파일을 읽고, 각 라인에 특정 키워드가 있는지 확인합니다. “apple”을 다른 키워드로 변경하면 다른 문자열을 찾을 수 있습니다.
이를 조건문을 이용한 효과적인 데이터 검색이라고 정의할 수 있습니다.