I am testing this customized code from C++ Primer 5th edition to read a sorted list of words using the less than sign from the windows command line while running the program and then ask the user to input a word to be searched for in the list; but the problem is that if I use the "less than sign" in the command prompt the code ignores further cin input requests however by entering a list of words manually and using ctrl+z (^Z) to terminate the cin input with an EOF and then ingoring that input and clearing the cin flags to goodbit (std::cin.clear();) the code recognizes the following cin input request. So what should be done to achieve the same result when using the less than < sign in command line to automate word list creation?
here is the example code:
so compile it and run it like this: a.exe < word_list.txt
and it fails to use "std::cin >> sought;" properly.
I have also commented out some tests for std::cin.rdstate() to show that the cin state is the same before and after receiving the eof by ignoring and clearing cin.
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> text;
std::string word;
//std::cout << std::cin.rdstate() << std::endl;
while (std::cin >> word)
text.push_back(word);
std::cout << "Enter a word to search:" << std::endl;
std::string sought;
//std::cout << std::cin.rdstate() << std::endl;
std::cin.ignore(1, std::cin.eof());
std::cin.clear();
//std::cout << std::cin.rdstate() << std::endl;
std::cin >> sought;
// text must be sorted
// beg and end will denote the range we're searching
auto beg = text.begin(), end = text.end();
auto mid = text.begin() + (end - beg)/2; // original midpoint
// while there are still elements to look at and we haven't yet found sought
while (mid != end && *mid != sought) {
if (sought < *mid) // is the element we want in the first half?
end = mid; // if so, adjust the range to ignore the second half
else // the element we want is in the second half
beg = mid + 1; // start looking with the element just after mid
mid = beg + (end - beg)/2; // new midpoint, we do not have operator+ for iterators
}
if (*mid == sought)
std::cout << "the result (" << sought << ") was found";
else
std::cout << sought << " was not found";
return 0;
}