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
}
}
Related
I am creating a simple login program.
#include <iostream>
#include <string>
using namespace std;
void showRegister()
{
string user;
string pw;
cout << "Enter your username:";
getline(cin, user);
cout << "Enter your password:";
getline(cin, pw);
cout << "You have successfully registered!" << endl;
writeIntoFile(user, pw);
showMenu();
}
void showMenu() {
int select;
do {
cout << "1. Register"<<endl;
cout << "2. Login" << endl;
cout << "3. Exit" << endl;
cout << "Enter your choice: ";
cin >> select;
} while (select > 3);
switch (select)
{
case 1:
showRegister();
break;
case 2:
showLogin();
break;
case 3:
default:
break;
}
}
int main()
{
showMenu();
return 0;
}
This is the result when I choose 1:
As you see, I can not enter username. In function showRegister(), when I add cin.ignore() before getline(cin, user), this is the result:
As I understand, getline() reads a line until it reaches character \n and skip the rest. So why in this case, two successive getline() commands (getline(cin, user) and getline(cin, pw) lead to the fact that I can not enter username?
The fact is getline takes input from buffer if something exists in buffer else it ask the user for value. What actually happens in your code is as soon as you enter value for select which is not greater than 3 it comes out of the loop after with a value you entered for select and the entered (which stands for \n) that you pressed get stored in buffer. So know when you come to getline for user it sees '\n' from the buffer as getline first check in buffer, so it skip the value insertion and buffer gets emptied and now when you come to getline that is used for password it ask the user for password as buffer was empty.
This will happen always after an switch from a formatted input to an unformatted input. Like from std::cin >> select to std::getline
The formatted input will read your integer "select", but not the following CR LF. (You pressed the enter key).
To solve that problem, you can simply write:
getline(cin >> std::ws, user);
std::ws will first consume the leading white space. Then the std::getline will work as expected.
Please read here about std::ws and do not forget to include <iomanip>
There are more severe bugs in your code. Like a cicrular call to "showMenu"
I'm having an issue using cin.ignore(), if I use it after a cin >> statement it doesn't seem to work and ends the program instead.
Here's my code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int number ;
int main () {
cin >> number;
cout << number;
cin.ignore()
return 0;
}
I am typing " 4 " (without quotes) at the prompt. I'm expecting it to prompt for an int (which it does) and then display that int until the user presses enter again. However as soon as I press enter on the first prompt the program closes. If I replace the cin.ignore() with a new cin >> then it waits until I enter data at that prompt before closing, however this way I have to put data into the prompt, I can't just press enter to close it.
I read about putting cin.clear() after the cin input but that didn't help. If I replace cin.ignore() with cin >> num2; then it works fine.
What am I doing wrong?
You can reset your input stream and ignore the rest of it if for example your user did not enter a valid int type as input. The while loop will not exit until number contains an actual integer. After that, if you want the program to wait until the user presses "Enter" or any other key, you can just call ignore again.
#include <limits>
#include <iostream>
int main()
{
int number;
// we need to enforce that the input can be stored as `int` type
while(!(std::cin >> number))
{
std::cout << "Invalid value! Please enter a number." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "Your number is: " << number << std::endl;
// wait for user to press Enter before exiting
// you can do this with ignore() x2 once for the newline
// and then again for more user input
std::cout << "Press Enter to exit." << std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
return 0;
}
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;
}
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.
I am here including a simple program that written in C++ where I am trying to use a parametrized constructor. My idea is to instantiate the class dynamically and capture the required task.
But whenever I run the program and enter the task 1 it simply prints the two lines (i.e. Enter Name.Enter Tel.No.). It is actually supposed to print "Enter Name." then input the name, And then again print "Enter Tel.No.".
How can I fix the issue? I have to use parametrized constructor dynamically while creating an object.
#include <iostream>
#include <conio.h>
#include <fstream>
#include <string>
using namespace std;
class myClass
{
string fullname,telephone;
public:
myClass(int taskType = 2)
{
if(taskType==1)
{
add_record();
}
else if(taskType==2)
{
//view_records();
}
else if(taskType==3)
{
//delete_record();
}else{
// custom_error();
}
}
void add_record()
{
cout << "Enter Name.\n";
getline(cin, fullname);
cout << "Enter Tel. No.\n";
getline(cin, telephone);
}
};
main (){
int myTask;
cout << "Enter a Task-Type. \n"
<< "1 = Add Record,"
<< "2 = View Records,"
<< "3 = Delete a Record\n\n";
cin >> myTask;
myClass myObject(myTask);
getch();
}
You are using cin >> myTask to read the first input. As you press enter to give the 1, selecting "Add Record", that 1 will be read from the buffer, but your newline will still be in the input buffer. Thus, the first getline will only read this off the buffer, producing an empty input for the line getline(cin, fullname);
The reason is that the first newline after the task type is not consumed by
cin >> myTask
so the fullname reading will only read an empty line and the "enter Tel.No" thing will be printed directly.
Insert a getline call after the cin >> myTask to fix this problem.
Also see this question.
This probably has nothing to do with your constructor, but rather with the mixing of cin >> and getline. Add a getline to a garbage variable after cin >> myTask and it should work.