How to let users put in only one character? - c++

so I have a text-based Adventure Game and its running smoothly but one of my "beta testers" noticed that he could select multiple numbers in the first cin spot and it would use those values for the rest of the game. Can I manually put a block on how many characters the user has to type?
Here's my program
#include <iostream>
#include <stdio.h>
#include <cstdio>
#include <cstdlib>
char Choice;
char my_name;
using namespace std;
int main()
{
printf("You come out of darkness.\n");
printf("Confused and tired, you walk to an abandoned house.\n");
printf("You walk to the door.\n");
printf("What do you do?\n");
printf("1. Walk Away.\n");
printf("2. Jump.\n");
printf("3. Open Door.\n");
printf(" \n");
cin >> Choice;
printf(" \n");
if(Choice == '1')
{
printf("The House seems too important to ignore.\n");
printf("What do you do?\n");
printf("1. Jump.\n");
printf("2. Open Door.\n");
printf(" \n");
cin >> Choice;
printf(" \n");
And so on, you get the gist of it

This is largely platform dependent and there is no easy catch-all solution, but a working solution is to use std::getline to read one line at a time and either ignore everything but the first character or complain if more than one was entered.
string line; // Create a string to hold user input
getline(cin,line); // Read a single line from standard input
while(line.size() != 1)
{
cout<<"Please enter one single character!"<<endl;
getline(cin, line); // let the user try again.
}
Choice = line[0]; // get the first and only character of the input.
Thus will prompt the user to enter a single character if they enter more or less (less being an empty string).

If you want the player to be able to press keys like 1, 2 or 3 without having to press enter, you're quickly getting into platform-specific code. On Windows, the old-school (and by old-school, I mean "dating back to the DOS days of the 80s") console way is with the conio routines.
There's nothing within standard C++ which defines that sort of interface, though.
Another approach is to use getline to get an entire line's worth of text every time, and then discard everything past the first character. That would keep you within plain C++, and fix your immediate issue.

Related

how do i detect a spacebar in a getline/cin and not ignore it or split it into two inputs?

lets say im making a getline. like I want to getline (cin, employeecode), and when the user
enters the employee code and they typed something like, A 05, I want to detect the spacebar in the center and then give an appropriate error message, how would I tackle something like that, I do not want to just just normal cin as that makes it into two input ( A as 1st input, 05 as 2nd input )and if I use cin.ignore() I cant detect the space bar as it ignores the space bar. I tried something with the ASCII value of spacebar, which is 32, so when it detects the the value of 32 it will do something but I dont know how to implement that either.
If you just want to read upto spacebar(that is a space) then you can use:
std::getline(std::cin, line, ' ');
The above will stop when a space is read. You can try out the program here.
So lets say you have the program:
#include<iostream>
int main(){
std::string line;
std::getline(std::cin, line, ' ');
std::cout<<line<<std::endl;
}
Then if the user enters the string Anoop Rana then only the first name Anoop is read into the variable line and everything after the space is not read into the variable line.
Edit
If you want to check whether the input given by the user has a space and then print out some message like invalid input if it has a space, you can use:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
getline(cin, name);
if(name.find(' ')!= string::npos)//check whether the input has a space or not
{
cout<<"Invalid input"<<endl;
}
else
{
cout<<"Input Is Correct"<<endl;
}
return 0;
}

stop inupt if input no double

first of all I'm sorry for my
bad english.
I'm trying to read some numbers and write them into a vector in C++.
This should go as long as the input is a double number and the
loop should be stopped if the user writes an 'a'.
My Question is how can I check if the input is 'a'.
Breaking the loop is not the problem
while(true){
if(!(cin>>userInput)){
//here i want to know if the input is 'a' or some other stuff//
//also i want to do some other stuff like printing everything//
//what already is in the vector//
//when everything is done; break//
}
else
//the input is a valid number and i push it into my vector//
'userInput' is defined as double so the loop will stop.
My Problem is, if the user write 'q' the loop stops but it's instantly stoping the whole program. My try look like this:
while(true){ //read as long as you can
cout<<"Input a number. With 'q' you can stop: "<<endl;
if(!(cin>>userInput)){ //here the progam stops when the input is anything but a number
cout<<"How many numbers do you want to add up?"<<endl; //there are numbers in a vector that should be added up
cin>>numberOfAdditions;
break;
}
So I have a vector with some numbers the users writes down (20,50,90,...)
When the input is equal to 'q' (in this example everything but numbers )
the loop stops and I want to ask the user how many numbers should be added.
The cout-command is displayed but the input is beeing skipped.
So my program is not reading how many valued from the vector I want to add.
I hope you know what I mean and I don't want to use two questions and two variables to save the input but if it's not working without it I'll change my program.
Have a nice Day :)
Because your Input variable is of type double you have to flush the Input from cin before reading again. Otherwise there is still a newline in the buffer.
Consider the following example:
#include <iostream>
using namespace std;
int main(){
double userInput;
int numberOfAdditions;
while(true){ //read as long as you can
cout<<"Input a number. With 'q' you can stop: "<<endl;
if(!(cin>>userInput)){ //here the progam stops when the input is anything but a number
cout<<"How many numbers do you want to add up?"<<endl; //there are numbers in a vector that should be added up
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cin.clear();
cin.ignore(INT_MAX,'\n');
cin >> numberOfAdditions;
break;
}
}
return 0;
}
The two Statements:
cin.clear();
cin.ignore(INT_MAX,'\n');
are flushing the Input stream until the newline is encountered.
The first answer already explains how to flush the cin stream after the user types in a char.
If you want to determine which character it was, you should define userInput as std::string. If the string is not "q" or "a" or whatever you are looking for, you have to cast the string to a double, just like this:
std::string str;
cin >> str;
if (str == "j")
// User typed in a special character
// ...some code...
else
double d = atof(str.c_str()); // Cast user input to double
Notice that the result of the cast is zero, if the user typed in any other string than the ones you especially look for.

How do I input variables using cin without creating a new line?

Whenever I input a variable using cin, after one hits enter it automatically goes to a new line. I'm curious if there's a way to use cin without having it go to a new line. I'm wanting to cin and cout multiple things on the same line in the command prompt. Is this possible?
You can't use cin or any other standard input for this. But it is certainly possible to get the effect you are going for. I see you're on Windows using Visual Studio, so you can use, for example, _getch. Here's an example that reads until the next whitespace and stores the result in a string.
#include <conio.h> // for _getch
std::string get_word()
{
std::string word;
char c = _getch();
while (!std::isspace(c))
{
word.push_back(c);
std::cout << c;
c = _getch();
}
std::cout << c;
return word;
}
It's not very good. For example, it doesn't handle non printing character input very well. But it should give you an idea of what you need to do. You might also be interested in the Windows API keyboard functions.
If you want a wider audience, you will want to look into some cross-platform libraries, like SFML or SDL.
you can also use space for input instead of enter
something like this:
cin >> a >> b >> c;
and in input you type
10 20 30
then
a=10
b=20
c=30
As others have noted, you can't do this with cin, but you could do it with getchar(). What you would have to do is:
collect each character individually using getchar() (adding each to the end of a string as it is read in, for instance), then
after reading each character, decide when you've reached the end of one variable's value (e.g. by detecting one or more ' ' characters in the input, if you're reading in int or double values), then
if you've reached the end of the text for a variable, convert the string of characters that you've built into a variable of the appropriate type (e.g. int, double, etc.), then
output any content onto the line that might be required, and then
continue for the next variable that you're reading in.
Handling errors robustly would be complicated so I haven't written any code for this, but you can see the approach that you could use.
I don't think what you want to do can be achieved with cin. What you can do is to write all your input in one line, with a delimiter of your choosing, and parse the input string.
It is not possible. To quote #Bo Persson, it's not something controlled by C++, but rather the console window.
I can't comment but if you leave spaces between integers then you can get the desired effect. This works with cin too.
int a, b, c;
cin>>a; cin>>b; cin>>c;
If you enter your values as 10 20 30 then they will get stored in a, b, and c respectively.
just use the gotoxy statement. you can press 'enter' and input values in the same line
for eg. in the input of a 3*3 matrix:
#include<iostream.h>
#include<conio.h>
void main()
{clrscr();
int a[20][20],x,y;
cout<<"Enter the matrix:\n ";
for(int r=2;r<7;r+=2)
for(int c=2;c<7;c+=2)
{gotoxy(c,r);
cin>>a[r][c];
}
getch();}

C++: how do I check if the cin buffer is empty?

How do you check to see if the user didn't input anything at a cin command and simply pressed enter?
When reading from std::cin, it's preferable not to use the stream extraction operator >> as this can have all sorts of nasty side effects. For example, if you have this code:
std::string name;
std::cin >> name;
And I enter John Doe, then the line to read from cin will just hold the value John, leaving Doe behind to be read by some future read operation. Similarly, if I were to write:
int myInteger;
std::cin >> myInteger;
And I then type in John Doe, then cin will enter an error state and will refuse to do any future read operations until you explicitly clear its error state and flush the characters that caused the error.
A better way to do user input is to use std::getline to read characters from the keyboard until the user hits enter. For example:
std::string name;
getline(std::cin, name); // getline doesn't need the std:: prefix here because C++ has ADL.
ADL stands for argument-dependent lookup. Now, if I enter John Doe, the value of name will be John Doe and there won't be any data left around in cin. Moreover, this also lets you test if the user just hit enter:
std::string name;
getline(std::cin, name);
if (name.empty()) {
/* ... nothing entered ... */
}
The drawback of using this approach is that if you want to read in a formatted data line, an int or a double you'll have to parse the representation out of the string. I personally think this is worth it because it gives you a more fine-grained control of what to do if the user enters something invalid and "guards" cin from ever entering a fail state.
I teach a C++ programming course, and have some lecture notes about the streams library that goes into a fair amount of detail about how to read formatted data from cin in a safe way (mostly at the end of the chapter). I'm not sure how useful you'll find this, but in case it's helpful I thought I'd post the link.
Hope this helps!
cin will not continue with the program unless the user enters at least 1 character (enter doesn't count). If the user doesn't give ANY input, cin will just keep waiting for the user to give input and then press enter.
The Simple way >>
{
char X=0; // ASCII( 0 ) means a NULL value
cin>>X;
if(X==0 || X==10) // ASCII( 10 ) means ENTER
cout<<"User din't enter ANYTHING !! ";
}
But a simple problem is....
cin just won't allow you to move further without entering a character
by character here i mean a DIGIT or alphabet or special symbol , not space, enter null etc
Hope this solves your problem, if it doesn't, I'll be glad to help just let me know.
int main(){
string str[100];
std::cout<<"Hello how are you ? \n";
std::cin>>str;
if(str.length() > 0){
// If input is seen
}
else{
// If input is not seen
}
}
Any problem let me know.

cin.get in a while loop

I'm trying to get input from user and give output until s/he presses 'n'. It doesn't seem to work. Is problem in scanf or cin.get? When I press y it just takes "tekrar" as an input, thus gives "y" as output and goes into a loop. Also, doesn't stop when i give n as tekrar input.
char cevap[300]="";
char tekrar='y';
while (tekrar!='n')
{
cin.get(cevap,300);
cout<<cevap<<endl;
cout<<"Again? (y/n)";
scanf("%c",&tekrar);
}
output:
Hello
Again? (y/n)
y
Again? (y/n)
y
Again? (y/n)
n
Again? (y/n)
n
...
Mixing the various input methods on istream (get, getline, operator>>) can be fraught with peril if you're not aware of which methods leave the delimiter character in the stream and which don't, and handle them accordingly.
In this case, get will read 300 characters of input or input up until the newline, whichever happens first. The newline will not be extracted, and so will remain in the stream. That means your call to scanf() will read the newline and stop, leaving the y or n you just typed in the stream.
There are several ways to reorganize this code to make it do what it seems like you want. This is one way:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string cevap;
char tekrar='y';
while (tekrar!='n')
{
getline(cin,cevap);
cout<<cevap<<endl;
cout<<"Again? (y/n)";
tekrar = cin.get();
cin.ignore();
}
return 0;
}
This uses std::string and the non-member getline to read input in such a way as to not require you to be limited to 300 characters (not strictly speaking related to the question, but good practice usually). getline consumes and discards the delimiter, but get, used to read the continuation input, doesn't, so we discard it manually via ignore.
Use cin operator>> to read from stdin, instead of scanf:
string cevap;
char tekrar='y';
while (tekrar!='n')
{
getline(cin, cevap);
cout<<cevap<<endl;
cout<<"Again? (y/n)";
cin >> tekrar;
cin.get();
}
Edit: fixed the infinite loop. You should use std::string instead of a simple char array.