Testing if user hit enter(while still testing for good input) - c++

I have a loop that i want to exit upon the enter key hit at the first cin, but i'm having trouble getting the program to work correctly. Currently i have:
while(running) {
cout << "enter word: ";
getline(cin,starting);
if(ladder.validWord(starting))
running = false;
else if(starting.empty())
return 0;
else
cout << "invalid word...\n";
}
I need to extract good input, while still testing for the enter key hit. Currently this still exits the program, and gives me some weird jumble(at the end of the program) that seems to be cut from my directory on the command line, such as:
g-dev#gdev-virtualBox:~/folder/ComputerProgramming/Wor$ dLadder
thanks for the help!

getline IS your test. getline only returns when someone hits enter.
// extract to string
#include <iostream>
#include <string>
#include <cstdlib>
std::string getInput(std::string prompt){
std::string name;
std::cout << prompt;
std::getline (std::cin,name);
if (name == "")
exit(1);
return name;
}
main ()
{
std::string name;
while (name != "poo"){
name = getInput("enter someting good:\n");
}
std::cout << "Hello, " << name << "!\n";
return 0;
}

I don't know whether this will help you or not but you can at least use it as a possible solution to your problem. When I want my program to wait for the user to hit enter this is what I usually do:
cout << "Press <enter> to continue...";
// this ignore statement will wait until the user presses <enter>
cin.ignore(numeric_limits<streamsize>::max(), '\n');
I hope it helps.

Related

How do I use the enter key to create new line, rather than inputting string?

I have to write a program that allows the user to enter a multiline poem, pressing the enter key to create a new line in the poem. All lines of the poem need to be stored in a single string, and I'm not sure how to concatenate the "\n" to user input. Additionally, once the user is done with the poem, I'm not sure how to then move on and execute further code in the program.
Here is the code I have so far:
/*
Poetry In Motion; Cortez Phenix
This program allows the user to make a poem, and the program contains a
poem game. The most notable features are loops controlled by the user.
*/
#include <string>
#include <iostream>
using namespace std;
void makePoem()
{
string user_input;
cout << "Enter a poem of your own creation, one line at a time.\n";
cout << "Type 'quit' to exit the program.\n\n";
cout << "Type your poem, pressing the enter key to create a new line.\n\n";
cin >> user_input;
if (user_input == "quit")
{
cout << "\nGoodbye! Have a great day.\n";
}
else
{
getline(cin, user_input);
}
}
int main()
{
makePoem();
return 0;
}
Apologies if this question is too vague or such. Thanks for the help.
You need to read the user's input in a loop, appending each line to your target string, eg:
/*
Poetry In Motion; Cortez Phenix
This program allows the user to make a poem, and the program contains a
poem game. The most notable features are loops controlled by the user.
*/
#include <string>
#include <iostream>
using namespace std;
void makePoem()
{
string poem;
string user_input;
cout << "Enter a poem of your own creation, one line at a time.\n";
cout << "Type 'quit' to exit the program.\n\n";
cout << "Type your poem, pressing the enter key to create a new line.\n\n";
while (getline(cin, user_input))
{
if (user_input == "quit")
break;
poem += user_input;
poem += '\n';
}
cout << "\nGoodbye! Have a great day.\n";
}
int main()
{
makePoem();
return 0;
}
This looks like a homework problem so I wont give you actual code but here are some clues :
You need a loop that keeps going until the user enters "quit"
You then simply add the user input to the user_input string using the += operator
To add a newline to a string you add "\n" ex : user_input += "\n";

Waiting for Input C++

My assignment dictates that unless something is entered by the keyboard, nothing will happen. However, I cannot prompt the user to enter anything. My loop looks something like this:
while(true){
"Enter a string to continue: ";
//wait for input
//based on input, do this.
}
The program basically pauses until the user enters a string input without being prompted to, if that makes sense.
The terminal will look blank until the user enters something and then my program kicks in based on the input. Would a simple cin work?
you will need to create a string variable to hold the users input. For example,
string name;
cin >> name;
cout << "you entered: " << name << endl;
now name will store the users input.
You may want this:
#include <iostream>
#include <string>
int main(void) {
for(;;){ // same meaning as while(true){
std::string str;
std::cout << "Enter a string to continue: " << std::flush;
std::cin >> str; // or std::getline(std::cin, str);
// based on the input, do something
}
}

Program that takes a sentence and outputs # of vowels, consonants, etc

enter code here
int main()
{
std::string input;
std::cin >> input;
while (input != "quit")
{
// do stuff
std::cin >> input; // get another input
}
return EXIT_SUCCESS; // if we get here the input was quit
The problem is, it isn't prompting the user to enter words at all. If I enter "quit", it ends, so that's working fine. Otherwise, if I enter in anything else, then enter quit, it just quits as well. What should I do to rectify that?
Through my research, I was able to find a similar program here which uses case, but that seems a bit tedious to me. I have been instructed to use the isalpha function, which accepts a single character as a parameter and returns a Boolean indicator as to whether or not the character is a letter.
Try this small illustrative program:
#include <iostream>
#include <cstdlib>
int main(void)
{
std::cout << "This is a prompt, enter some text:\n";
std::string the_text;
std::getline(std::cout, the_text); // Input the text.
std::cout << "\n"
<< "The text you entered:\n";
std::cout << the_text;
std::cout << "\n";
// Pause the program, if necessary.
std::cout << "\n\nPaused. Press Enter to continue...\n";
std::cin.ignore(10000000, '\n');
// Return status to the Operating System
return EXIT_SUCCESS;
}
As you can see, outputting an instructional phrase before an input is known as prompting the User.
Edit 1: Prompting in a while loop
In your case, you need to prompt the user before the input:
while (input != "quit")
{
// Do stuff
std::cout << "Enter text or \"quit\" to quit: ";
std::cout.flush(); // Flush buffers to get the text on the screen.
std::cin >> input;
}

Why can't I write to a file if it is located within an if statement?

I am trying to create a very simple program that writes to a file, but can't understand why it won't let me write to a file if I put it within an if statement! Here's the code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
void readFile();
int main()
{
string line;
string today;
string readOrWrite;
cout << "Do you want to write to a file or read a file? " << endl;
cout << "Type \"write\" or \"read\" ";
cin >> readOrWrite;
if (readOrWrite == "read")
{
readFile();
}
else if (readOrWrite == "write")
{
cout << "How are you today? " << endl;
getline(cin, today);
ofstream myJournal;
myJournal.open("Journal.txt", ios::app);
myJournal << today << " ";
myJournal.close();
}
else
{
return 0;
}
return 0;
}
void readFile()
{
ifstream myJournal;
myJournal.open("Journal.txt");
string line;
if (myJournal.is_open())
{
while (getline(myJournal, line))
{
cout << line << endl;
}
myJournal.close();
}
else
{
cerr << "Error opening file ";
exit(1);
}
}
When I move it out of the if statement, it works smoothly and is able to write to the file, but when I place it inside, it opens the program, asks me the "Do you want to write to a file or read a file? ", I type "write", then it says "How are you today? " and then ends the program, printing "Press any key to continue...". Any help?
it says "How are you today? " and then ends the program, printing "Press any key to continue...". Any help?
std::istream::ignore should help in that case you are encountering.
cout << "How are you today? " << endl;
cin.ignore(10, '\n'); // Inserted
getline(cin, today);
Why do we need that in between?
It takes out 10 characters, which is enough amount of length, from the buffer and stops if it encounters a newline, which is '\n'. (Remember that you press the key 'enter' after typing "wrtie")
By doing so you can move on to the next new line, preventing std::cin from any parse failure.
More info : http://www.cplusplus.com/reference/istream/istream/ignore/

Password function and arrays

I'm writing a simple password program, but the else if statement always applies, even if the password is put in correctly. This works fine if I use a single char instead of an array, and change "hotdog" to 'h', and I think it might have something to do with unseen characters, like a space or return. I was sure cin.ignore() took care of return/enter.
Sorry, I'm fairly new to programming.
#include <iostream>
int main()
{
std::cout << "What is the password?\n" << std::endl;
char password[20] = "NULL";
std::cin >> password;
std::cin.ignore();
std::cout << password << " is your entry?\n";
if (password == "hotdog")
{
std::cout << "Correct!";
}
else if (password != "hotdog")
{
std::cout << "Incorrect!";
}
else
{
}
std::cin.get();
}
Firstly, change char password[20] to string password. This prevents a buffer overflow if they type in more than 20, and it enables you to use == for string comparison.
The code std::cin.ignore() ignores a single character. You want to actually ignore the entire remainder of the line. There is no way to ignore "everything else typed so far" because there may have been characters typed which are still buffered. In practice, it works well to treat input as a series of lines.
The most accurate way to ignore the rest of the line is to ignore all characters up to and including '\n', which appears in the input stream at the end of the line (by definition).
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
which may require #include <limits>. Another way is to read a string and discard it:
std::string t;
std::getline( std::cin, t );
NB. Check your understand of if...else . Once you have if ( condition ), then the next else will already get everything that was not in that condition. It's pointless to actually write else if ( !condition ); and your final else { block can never be entered, because the previous two conditions were exhaustive.
The problem is with how you are using the if-else statement. Try this code out:
#include <iostream>
int main()
{
std::cout << "What is the password?\n" << std::endl;
char password[20] = "NULL";
std::cin >> password;
std::cin.ignore();
std::cout << password << " is your entry?\n";
if (stricmp("hotdog", password) == 0)
{
std::cout << "Correct!";
}
else
{
std::cout << "Incorrect!";
}
std::cin.get();
}
When I take your code and compile it, even the term hotdog does not work properly, I obtain the following:
What is the password?
hotdog
hotdog is your entry?
Incorrect!
As suggested above, a string is a better method and works as intended based on your requirements. Here is sample replacement code that works as intended (with this code spaces are allowed, with the other answers, spaces are not, it all depends what is intended):
#include <iostream>
#include <string>
using namespace std;
int main (int argc, char ** argv)
{
cout << "What is the password?\n" << endl;
string password = "NULL";
getline(cin, password);
cout << password.c_str() << " is your entry?\n";
if (password == "hotdog")
{
cout << "Correct!";
}
else if (password != "hotdog")
{
cout << "Incorrect!";
}
else
{
// Added from original; however, this should never occur
cout << "Else?";
}
system("pause");
return 0;
}
Output of Replacement Code
What is the password?
hotdog
hotdog is your entry?
Correct!
You had to use strcmp() function to compare strings properly in c++,so I added the cstring library:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main(){
string password;
cin >> password;
cout << password << " is your entry?\n";
char hd [7] = "hotdog";
if (strcmp(password.c_str(),hd) == 0){
cout << "Correct!\n";
}
else if (strcmp(password.c_str(),hd) != 0){
cout << "Incorrect!\n";
}
else{
cin.get();
}
}