C++ Console not taking keyboard input - c++

Resolved
I'm using Microsoft Visual Stuido 2017 and built a basic console utility program. When using the debug mode(F5) everything works flawlessly. Then I chose to batch build and see if I could run the .exe. The .exe runs my welcoming message and even greets me with a flashing cursor but won't accept any kind of keyboard input. I try hitting random letters on my keyboard and none pop up; oddly though alt + F4 works so my keyboard likely isn't the issue. I am honestly one hundred percent clueless as to what it might be. It should be noted my save location differs in a few ways. Could it be an issue with my system and not the program?
Screenshot
I have iostream and other appropriate C++ standard libraries included through my header files
int main() {
cout << "Welcome to FTC console commands" << endl
<< endl << "Please enter a command or 'HELP' for help" << endl
<< "You can exit at anytime by typing 'EXIT'" << endl; //Welcome
while (true) { //main loop
league1 = load();
string Input; //Input
cin >> Input;
system("CLS");
if (Input == "EXIT") break; //Checking where to go depending on Input
else if (Input == "ADD_MATCH") addMatch(league1);
else if (Input == "ADD_TEAM") addTeam(league1);
else if (Input == "HELP") help();
else if (Input == "RANK") rankings(league1);
else if (Input == "SAVE") save(league1);
else cout << "Invalid Input... try again or see 'HELP'" << endl;
}
return 0;
}

load(); was referencing a file that didn't exist, so even if it made its own, it lacked the footer I defined and it wouldn't stop reading the document. Simply created the document it was trying to load and added the footer.

Related

GetLine to compare strings works once then the compare doesn't work after

while((addRemove == "R" || addRemove == "r") && continueLoop == true)
{
for(int i = 0; i < choreVector.size(); i++)
{
if(choreVector[i] != "")
{
cout << choreVector[i] << endl;
}
}
cout << endl;
cout << "Enter value to add to remove from the list" << endl;
cin.ignore();
getline(cin, userValue);
cout << endl;
for(int j = 0; j < choreVector.size(); j++)
{
if(userValue == choreVector[j])
{
choreVector.erase(choreVector.begin() + j);
}
}
cout << "Would you like to remove another item from the list(y/n)" << endl;
getline(cin, userValue);
cout << endl;
if(userValue == "n" || userValue == "N")
{
continueLoop = false;
}
}
So my problem is that I have a list of chores in a vector with spaces with items like:
'Take out garbage'
'Walk the Dog'
My problem is that the user has the option to remove from the vector from Keyboard input so i've been using getline for cin input.
The Getline works flawlessly on the first run to remove any element but fails on the second run through and won't remove an element after removing the first. I have cin.ignore before the GetLine which to my knowledge cleared the buffer and would ignore any data from previous cin.
Probably something stupid im overlooking but if anyone could help that would be great.
From what I gather, the issue seems to lie with your IDE. A typical IDE will have some sort of "Output" or "Messages" tab that is configured to show the output of the window, because it has been auto-configured to pipe the output from the compiler to this window. Depending on your IDE, they may or may not also support input in this window. At worst, input can be very buggy, half working, half broken. I generally assume any IDE I use does not support input in that window, and will either compile the program manually on the command-line / terminal, or I know code::blocks and Visual Studio open a console window, which has support for user input and output, and will make sure to use that.

I am trying to end my C++ program when the user presses 'Ctrl-D'

my program has read in a large file of words (a dictionary) and inserted them all into a hash table. I am prompting the user to lookup a word and I want them to be able to terminate the program by pressing Ctrl-D. This is what I have tried but when I press Ctrl-D it just gets stuck in a loop printing out what I have in the else statement. I am using Unix. I have attempted looking this up on this website and nothing was working that I was trying hence why I am asking my own question. Any thoughts? PS. The transform is to make the user input all uppercase to match the file I am reading from.
void query(){
bool done = false;
string lookupWord;
while(!done){
cout << "Type a word to lookup or type ctrl-D to quit: ";
cin >> lookupWord;
if(atoi(lookupWord.c_str()) == EOF)
done = true;
else{
transform(lookupWord.begin(), lookupWord.end(), lookupWord.begin(), ::toupper);
cout << endl << "Word: " << lookupWord << endl;
cout << endl << "Definition: " << myDict.lookup(lookupWord) << endl << endl;
}
}
}
atoi(lookupWord.c_str()) == EOF
This doesn't do what you think it does. This checks the return value of atoi() and compares it to EOF. EOF is typically defined as -1. So, the code ends up setting done only when -1 is typed in. Which is not what you want.
std::istream has a convenient operator bool that tests whether the file stream is in a good state. So, all that really needs to be done is:
if (cin >> lookupWord)
{
// Your existing code is here
}
else
{
done=true;
}

C++ Custom User input command - Call Varibles

I appreciate the help. I am really bad at c++ and i like constructive criticism. im building a text based game and im currently setting up all the functions and systems. my problem is that i need a way for the user to be able to, at any time, type in somthing like "stats" and have them printed on the screen. currently i do not know how to do that. i dont know if this is possible but would i be able to have the stats always show. you know when your in the cmd and where it shows what directory your in, i would like it to be right there but in my game. heres the source, i know its cluttered
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <ConsoleColor.h>
using namespace std;
//STAT VARS
int hp=100;
//Login VARS
const string USERNAME = "user";
const string PASSWORD = "123456";
string username, password;
int main()
{
login:
cout<< "================" <<endl;
cout<< "======Login=====" <<endl;
cout<< "================" <<endl;
cout<< "\n Username: ";
cin >> username;
cout<< endl;
cout<< "Enter Password : ";
cin >> password;
cout<< endl;
if(username == USERNAME && password == PASSWORD)
{
system("cls");
cout << green << "CORRECT" <<white<< endl;
Sleep(1000);
system("cls");
goto correct;
}
else
{
system("cls");
cout <<red<< "Invalid login details" <<white<< endl;\
Sleep(1000);
system("cls");
goto login;
}
correct:
char name[20];
cout <<"What do they call you boy?" << endl;
cin.getline(name, 20);
cout << "You should keep moving, " << name << ".Were running out of daylight." << endl;
cout << "\n ***** Press Any Key To Continue *****" << endl;
_getch();
return 0;
}
Remove goto
while ((username != EXPECTED_USERNAME)
&& (password != EXPECTED_PASSWORD))
{
// No need to clear the screen.
cout<< "\n Username: ";
cin >> username;
cout<< endl;
cout<< "Enter Password : ";
cin >> password;
cout<< endl;
}
You should not have your identifiers differ only by case. Although the compiler will treat username different from USERNAME, Good Coding Guidelines state that identifiers (names) should be more different. This is why I used username and EXPECTED_USERNAME in the example above. Something about better readability.
Consistency
You used the std::string type for the username, yet you use char [20] for the boy's name. Be consistent, use std::string for all the types.
Pause for Enter
Trying to detect a keypress without pressing Enter is not as portable as waiting for them to press enter.
Try this:
std::cout << "Press ENTER when ready.\n";
std::cin.ignore(100000, '\n);
Stop Clearing The Screen
Very annoying. There may be information that could be retrieved by scrolling back, but you insist on clearing the screen. Bad form.
Don't Sleep
The input will wait for the User to press the Enter key, so there is no need to sleep. The sleep is not portable.
Also, if you are going to fool people about entering bad passwords, you will need to sleep when they enter a valid password too.
Don't use non-portable console tricks
In modern times, console programs are run in a window; maybe a terminal emulator. The console windows are not standard. Don't rely on colors or clearing the screen or moving the cursor. Display what you need to each time.
If you want to use graphics, develop for a GUI application.
Edit 1: Command Driven Architecture
You will need to have a design or architect following this psuedo code:
While true
{
Input User's text
if User entered quit command, exit program.
else Execute a function based on the Users text
}
This will allow the User to enter the command "stats" at any time.
If you want the User to enter commands while you are displaying text, it is possible, but adds more complication.
The actions of the game should be quick enough that the next command prompt is displayed before the User can enter "stats".

C++ change canonical mode in windows

After finding a bunch of threads on this I did not find any on Windows, only Linux, Ubuntu etc.
In short what I am trying to find out is how to turn canonical mode off so that input in the console results in instant input without having to press enter.
Longer version. This is what I am trying to do right now:
When the PGM is pausing (text based game) the user is asked to enter an arrow key to move the player around on the 2D array. But cin.get(), cin.ignore() and some other things I've tried all require pressing enter before it will continue.
The infamous system("pause>nul"); does actually work, but as I've read in various other places is very bad practice.
This is part of the code. the cout statements are only for testing purpose:
//While loop
if(GetAsyncKeyState(VK_UP)){
cout << "up" << endl;
}
else if(GetAsyncKeyState(VK_DOWN)){
cout << "down" << endl;
}
else if(GetAsyncKeyState(VK_LEFT)){
cout << "left" << endl;
}
else if(GetAsyncKeyState(VK_RIGHT)){
cout << "right" << endl;
}
else{
break;}
//pauze and check for arrow key input here
You can use getch also on windows:
I know it is C, and you got the deprecated warning, but it works...
this code run in a loop till you press Enter:
check what happen when you press an arrow key...
#include <stdio.h>
#include<conio.h>
int main ()
{
int c;
do {
c=getch();
printf("%d\n",c);
} while (c != 13);
return 0;
}

else if looping quandry

I am in the second phase of a project where I need to extend my program into a menu driven application to query the database I have on a .txt file. So, my trouble is that I cannot get my loop to be perpetual. It always terminates when it initializes from one option to the next. Here is the snippet of my code that is my int main:
int main ()
{
char Q,q;
char S,s;
char task;
string pathname;
string z;
int count=0;
cout << "Welcome to Jason Rodriguez's Library Database." << endl;
cout << "Please enter the name of the backup file: ";
cin >> pathname;
ifstream inFile(pathname.c_str());
while(!inFile.eof())
{
getline(inFile,z);
count++;
}
while (task != 'Q' || task != 'q') {
cout << count << " records loaded successfully." << endl;
cout << "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All: ";
cin >> task;
if ((task == 'Q')||(task =='q'))
{
cout << "Program will now terminate";
break;
}
else if ((task == 'S')||(task =='s'))
{
showAll (loadData (pathname));
cout << endl;
cout << "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All: ";
cin >> task;
}
}
}
I need to add two more options into the loop on top of these two but I figured I should get the first two working correctly first. The other two should be plug & chug after that. Basically what I was trying to do is say if the user enters Q or q, terminate the program. Else, if user hits S or s, activate showall function and after ward, go back to the original query. It isn't working though. Assistance is welcome and appreciated.
Menus almost always require loops - especially ones that require the user to enter the correct choice input. The most applicable one in a case like this is the while loop - but essentially, any other loop variant can be used.
UPDATE:
int main ()
{
char task;//this is the only char needed. Your other chars were redundant
string pathname;
string temp;//I changed z to temp to better reflect its purpose
int count=0;
cout << "Welcome to Jason Rodriguez's Library Database." << endl;
cout << "Please enter the name of the backup file: ";
cin >> pathname;
ifstream inFile(pathname.c_str());//this is potentially a problem in that you aren't verifying that the pathname is a valid one
//you did not check to see that your file was open, otherwise there is no way to tell that you successfully opened the file
if (inFile.is_open()) {
//while(!inFile.eof()) is a character by character read and comparison
//made your life easier by shortening it down to this - which ensures
//that a line is read. (Much faster and more readable)
while(getline(inFile,temp))
{
count++;
}
inFile.close();//always close a file after you've used it
//At this point the entire file has been read. So, this is where this message SHOULD be
cout << count << " records loaded successfully." << endl;
}
else {
//if there was an error opening the file (i.e. wrong path, or it simply does not exist), this will be displayed
cout << "There was a problem opening your file" << endl;
exit(0);//and the program will terminate
}
while (task != 'Q' || task != 'q') {
cout << "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All: ";
cin >> task;
if ((task == 'Q')||(task =='q'))
{
cout << "Program will now terminate";
break;
}
else if ((task == 'S')||(task =='s'))
{
string author;
//showAll (loadData (pathname));
cout << endl;
cout << "Search an Author" << endl;
cin >> author;//get the author name to search from the user
//write code to search an author here
}
}
}
There are a number of issues with the code that you posted which I will forgo for the sake of brevity. Hence, note the following:
Your code was printing the same message per option (except for quit). Of course it would appear that it didn't work. Each option is a different task. Print what each task does (similar to what I did).
You wish to search the file for an author, but you have not stored it. Look into a way of storing it that appeases your instructor.
It would be ideal for you to use switch in this case, considering the increasing complexity of your code.
Try breaking down each task into functions, and call them to make your main function readable. In fact, it is a good programming practice for your main function to be as small as possible.
And, as juanchopanza quite rightly pointed out: you have some fundamental issues with C++. Try doing some more exercises and do more examples from a good C++ book.