Hello, i've been working on a program about input and output in a .csv file.
It works, but my problem is that i cannot find a way to stop a while loop using a key press (Esc).
I tried with !GetAsyncKeyState(VK_ESCAPE) but it doesn't work.
This method works, but it's not what i'm really searching for.
I'd like to break the loop not just at the end but anytime during its iterations, in this case by pressing a virtual key (Esc) or by any other method that can break a loop during a cin call.
I'm still a beginner so i don't really know if what i want to do is possible. If i'm trying to do something that is impossible let me know
I do not know if it is impossible, but this is one Windows API function I do not very often and have not for awhile.
What I have found if that
1 2
while(!GetAsyncKeyState(VK_ESCAPE))
{
does not work. Somehow this function call needs to be inside the while loop.
The problem I found is that the formatted input does not recognize the "Esc" key or the "enter" key by its-self. It will accept the "enter" key is you type something before it first.
The down side of C++ is that it has no function to accept just a single key press and move on. I am comparing this to the old C "getch()" which is for the most part no longer used as not every compiles has the "conio.h" header file or supports it.
Maybe someone more use to this will have some ideas.
void f()
{
string Title, Author, Genre;
// Don't split the declaration of Library and it's initialization
ofstream Library("Library.csv", ios::app);
system("cls");
// End loop with Ctrl-Z (Ctrl-D on linux)
while (cout << "Title: ", cin >> Title)
{
// Or end loop by entering an empty Title
if (Title.empty())
break;
cout << "Author: ";
cin >> Author;
cout << "Genre: ";
cin >> Genre;
// Don't use string literals if you really want a character literal.
Library << Title << ';' << Author << ';' << Genre << '\n';
}
system("cls");
// Avoid saying "close" by proper scoping.
// Library.close(); // Library automatically closes when it goes out of scope
}
mimic of getch is challenging. Every OS has some way to do it, but c++ itself does not really.
windows should have an onkeypress event, but I do not know exactly how to tap it from a console program on current versions.