How can i handle invalid input to cin(cpp) - c++

when i use the code below,
char command;
cin >> command;
i want to get only ('a','c','d') as inputs.
In other alphabet(int) cases, i can solve the problem using 'switch statement'
But when someone types multiple characters, my program doesn't know what is the problem.
Just, take one charcter of multiple characters.
In conclusion, I want to detect the multiple character input case.
And this happens, i want to print error, then program to keep running.

Related

How to take this kind of a STDIN inputs in c++?

In lots of hackathon they provide testcases. So in those test cases they provide inputs in different ways through STDIN. This is one of the situation I struggle at all.
This is one kind of a input: (This is one testcase)
Mike
John
Ahmed
Sangha
Daniel
Ann
So here I have 6 inputs. But they don't provide number of inputs. So I can't use for loop or while loop to take this input. Because I don't know how many iteration I should do. So I have to take inputs until end. But this is not a input from a file. So I can't use EOF as well. This input is from STDIN. So how can I take this kind of input and store it in an array? Also I don't know how many elements should create in array. Because I don't know how many number of inputs are there. (different testcases may contain different number of inputs). How can I solve this kind of a problem?
Thank you so much for the help!
You should be able to use EOF, because stdin is a file (at least on linux)
The input here clearly shows you how many entries are presented. Note that each entry is on a newline so, considering it as a delimiter, you can parse your input stream and get the entries separated and also get the count of entries.
C++ getline() does this exactly:
istream& getline( istream& is, string& str, char delim );
Last param to getline is optional because it uses '\n' as default.
If you want to do it the raw way, you could setup a file pointer and do a lookahead for '\n' and read everything before it into new item of a variable array(vector) ...do this repeatedly until u reach EOF of stream(or filestream)

C/C++ , How to deny inputting char/string when waiting for the user to input a int , float or whatsoever?

A beginner question !
How to oblige the user to only input a number (int,float,long..) so he cannot input a char or a string when you're waiting for a number :D thanks
In general input validation can be done in two distinct ways:
Validate input after the user entered his input, and display an appropriate message, along asking the user to re-enter valid input.
Keep a state machine (FSM) that knows which input format is expected at a particular point . When the user is going to input particular characters, these are checked to fit for the current state's rules.
The 1st solution is easy to do, because you can check input operations for particular fields:
std::istream& is = <reference to any valid input stream>;
double value;
if(!(is >> value)) {
// Issue error message
}
The 2nd solution needs to peek for characters as they are typed in, and are immediately checked to become part of the input (and be echoed at the tty), or not. That's not possible in a simple, OS independent way.
Though there are techniques available, that enable you to restrict character inputs from std::cin according your current parser FSM state. Check this post for more information about how this can be achieved.
There aren't any standard C/C++ libraries to prevent the user from entering a string where a number is expected.
If you are using scanf or fscanf, you can check the value returned from the function to make sure that you were able to read the expected number of data.
If you are using std::cin or std::ifstream, you use fail() to check whether the operation succeeded or not.

Prompting User For Instructions

I am trying to write an infix calculator and I want to start the program off asking the user if he/she needs help or not. I have written the code that will offer instructions if the user inputs 'y' or 'n', however, in both cases, the program ends without allowing the user to enter an infix expression and running the rest of the program. It seems as though the program is breaking in main right after cout << "Expression?"; It does not give the option for the user to input anything after that.
When you use cin >> help, you're only reading one character, the y or n. The newline after that is left in the input buffer.
Then when the main function uses getline, it reads up to the next newline, which is the one that was left in the buffer by provideHelpIfNecessary. So it just reads a zero-length line, and that causes the while loop to break.
Use getline in provideHelpIfNecessary instad of reading just one character.

Data validation from getline in C++

I want to ask the user if they want to continue playing another round or quit. If they want to continue I expect them to enter two words in getline, but if they enter quit, I want to break;. Is this possible?
Can I check to see if the first letter is a "q" and then use putback if it is not? Or can I check the whole word and putback if it is not quit (I would not know the length of the word). Id there some other way I can approach this?
Thank you!
Yes.
I recommend using getline to read each line of user input. Then parse the string in order to determine what action to take. I don't see how a putback would be useful if it were possible. If necessary you can use a stringstream to get numeric info out of the string, or you can simply compare characters. It is up to you to determine the approach but there are a variety of ways in which you could design the program.
Take a look at this. Try to avoid the common gotchas associated with standard streams otherwise you will soon be googling for answers to other questions.
http://www.parashift.com/c++-faq/input-output.html

Good way to tokenize a string to store values? Or alternative for user input

Hello again Stackoverflow, I'm here again asking a question for my C++ programming class. The problem I am facing is mostly to due with user input from the keyboard. I need to be able to take the user input to decide what function to call and what arguments to give the function. For example something like add 5 would call the add function with the argument 5. At first I tried overloading the >> operator to take both a string and an int but the problem I ran into was the program was unable to take input without the int such as deletemax so I had to throw that idea out. So now I am back to tokenizing the input but we are not allowed to use Boost for this program so I came up with something like this using sstream
bool out = false;
string token;
string In;
int num;
do
{
cout << "heap> ";
cin >> In;
istringstream iss(In);
while(getline(iss, token, ' '))
{
cout << token << endl; //I know this is incorrect but just not what to replace it with
}
out = ProcessCommand (token, num); //Takes string and int to call correct functions
} while (out != true);
The problem lies in that I'm not quite sure how to correctly tokenize the string so I can get 2 string and convert the second string to an int. Can anyone offer me some assistance? I would greatly appreciate it. Also if there is a better way to go about this than I am trying I would also like to hear it.
Thanks for any help you can give me.
Googling "C++ string tokenize" will get you plenty of hits, with the first hit being on Stackoverflow. But you should take a stab at it. I'm guessing it's the point of the exercise.
You said "argumentS", which suggests that commands you support take varying numbers of arguments. I'd break it down like this:
read a line from the user
split line into 'tokens' on space boundaries, store tokens in a list
based on the first token in the list, choose a command to execute
pass the list of tokens to the command, so it can validate/interpret them as arguments
The tricky part is #2. Do you know about container classes yet? You can use vector<string> to store the chunks you parse. To do the actual parsing, you iterate through the characters of the string. Skip whitespace until you find a non-whitespace character (or run out of characters). Save this position: start. Then skip non-whitespace until you find whitespace (or run out of characters). Save this position: end. Copy the substring represented between from start to end and copy that to your token list.
Working out the actual details of this, making sure you don't have off-by-on-errors, etc. is going to be challenging if you've never done it before, which I'm guessing is the point.
You don't need to read in the whole of user input all at once.
For example you could read in the first bit of user input (the operation, add or deletemax, etc). From there depending on the operation you could continue to read arguments from input (in the case of add) or begin performing the operation immediately (in the case of deletemax).
One way would be to have a std::map of function names as keys and required number of arguments as values. You'd read a line of input, get the function name and then decide whether you need aditional arguments. I'd write a function that'd return a vector of arguments extracted from a string stream or an empty vector in case the input was invalid.