How to search for a word in text file with C++

2 Answers

0 votes
#include <iostream>
#include <fstream>
#include <string>

using std::cout;
using std::endl;

int main()
{
	std::ifstream ifs("d:\\data.txt");
	char s[80], word[] = "c++";
	bool found = false;


	while (!ifs.eof()) {
		ifs >> s;
		if (!strcmp(s, word)) {
			found = true;
			break;
		}
	}

	ifs.close();

	if (found)
		cout << "found" << endl;
	else
		cout << "not found" << endl;

	return 0;
}

/*
run:

found

*/

 



answered Jun 15, 2018 by avibootz
edited Jun 15, 2018 by avibootz
0 votes
#include <iostream>
#include <fstream> 
#include <string> 

using std::cout;
using std::endl;
using std::string;

int main(void)
{
	static const char *fileName = "d:\\data.txt";
	string s = "c++";
	bool found = false;

	std::ifstream ifs(fileName);

	if (ifs.is_open()) {
		while (ifs.good()) {
			string word;
			ifs >> word;
			if (word == s) {
				found = true;
				break;
			}
		}
	}
	else  {
		std::cerr << "Error open the file" << endl;
		return EXIT_FAILURE;
	}

	if (found)
		cout << "found" << endl;
	else
		cout << "not found" << endl;

	return EXIT_SUCCESS;
}

/*
run:

found

*/

 



answered Jun 15, 2018 by avibootz

Related questions

1 answer 106 views
1 answer 120 views
1 answer 218 views
1 answer 206 views
...