Hi everyone! so I have an issue I cannot figure out, basically when I simulate eof using ctrl + d the second use of cin is never used and skipped over, I have a check for cin.fail but after the clear it is valid so what is causing this? it also happens if i say give cin a char instead
is this unix?
regardless, give a call to clearerr() a try. Its a misnomer in this case, since its not an error, but it should clear the EOF flag and allow your stream to proceed. Clear() is not sufficient for the EOF state. To oversimplify it, clear removes data from the stream, but the ctrl-d eof flag sets a state, its not 'just text in the buffer' here.
cin and cout and streams generally have a fair number of special snowflake stuff buried in them.
This only works for c file streams (FILE*) - not C++ fstreams.
clear()
Sets the stream error state flags by assigning them the value of state. By default, assigns std::ios_base::goodbit which has the effect of clearing all error state flags. https://en.cppreference.com/w/cpp/io/basic_ios/clear
#include <vector>
#include <iostream>
int main() {
std::vector<int> vecOfInts;
std::cout << "Enter values for the vector: ";
for (int insert; std::cin >> insert; vecOfInts.push_back(insert));
if (!std::cin.eof())
std::cout << "Failed";
else {
int val {};
std::cin.clear();
std::cout << "\nEnter val to count how many are present: ";
std::cin >> val;
std::cout << "\nThere are: " << std::count(vecOfInts.begin(), vecOfInts.end(), val) << ' ' << val << "'s in the vector\n";
}
}
For Windows, ctrl_z is eof and has to be entered on a line by itself. Eg
Enter values for the vector: 1 2 3 1 2 3 1 2 3
^Z
Enter val to count how many are present: 1
There are: 3 1's in the vector
Thanks seeplus for the help with this! I really like the idea of using a for loop's header rather than a while loop + body like I had. yours is way nicer to read.
Also with regard to the ctrl_z thing, this was definitely the issue as my IDE (rider) would not let me use ctrl_z in its console (it just said do you want to undo last action) but building and running the program separately let me use ctrl_z like you said perfectly