Char or String? - c++

Does it matter if I use a string or char for a simple input function? (aka y/n)
This is what I'm using at the moment:
using namespace std;
string somestr;
getline(cin,somestr);
if(somestr.empty())
{ //do something }
else if (somestr == "y"){
//do something else
}
else{}
And if it makes more sense to user char what would be the equivalent char code to this?

Yes, it matters, because std::string cannot be compared with a char using ==. You can compare it with a string literal:
if (somestr == "y")
or you can test the initial element of the std::string:
if (somestr[0] == 'y')
In the latter case, you might want to check the length as well, otherwise you would accept such inputs as "yacht" and "yellow." Comparing with a string literal containing the expected text is probably a better choice for most use cases.

I think James McNellis gives good rationale for why you would use either case. Personally, if you're asking a "yes/no" question, I find the single character easier because it minimizes the number of different scenarios you have to deal with.
Here's some sample code that you could use to read an answer from the user via a single character:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
//keep looping until the user enters something valid
while(true)
{
char answer;
cout << "Does this sound good (y/n)? ";
cin >> answer;
if(answer == 'y' || answer == 'Y')
{
//user entered yes, do some stuff and leave the loop
cout << "You answered yes!" << endl;
break;
}
else if(answer == 'n' || answer == 'N')
{
//user entered no, do some stuff and leave the loop
cout << "You answered no!" << endl;
break;
}
else
{
cout << "You did not enter a valid answer. Please try again." << endl;
//if we got bad input (not 'y'/'Y' or 'n'/'N'), wipe cin and try again
cin.clear();
cin.ignore(numeric_limits<int>::max(),'\n');
}
}
}
If you're planning on reading more than a single character answer though, then I think you're probably fine with getline and doing your reasoning that way.

It is better to use char because you only need to store one character
using namespace std;
char chr;
getline(cin,chr);
if(chr == null)
{ //do something }
else if (chr == "y"){
//do something else
}
else{}

Related

Why does my if statement not run even if the condition is met?

I tried to make a simple program that asks the user a question and if the user answers correctly, it tells them that they are correct, but if they don't, it tells them to try again, and the code runs again. I did this using a while loop, if they answer correctly it breaks out of the while loop. But when i tested it even when i get the correct answer, it doesn't break out of the loop.
#include <iostream>
int main() {
int answer;
while (1 < 2) {
std::cout << "What is 3 + 5?";
answer = std::cin.get();
if (answer == 8) {
std::cout << "You are correct!";
break;
}
else {
std::cout << "Wrong answer! Try again";
}
}
}
Because the get function returns a character.
There is no existing encoding where the character '8' is equal to the integer 8.
Either you need to convert the character to its corresponding integer:
(answer - '0') == 8
Or compare against the character:
answer == '8'
If you really want to read integers, then I suggest you read using the input operator >> instead:
std::cin >> answer;
I think you should assign answer like that:
std::cin >> answer;
because get function gets the input as string and your answer variable is int.
So in the if statement, it checks "8" == 8 and that returns false.
Concluding, the whole code must be like that:
#include <iostream>
int main() {
int answer;
while (1 < 2) {
std::cout << "What is 3 + 5?";
std::cin >> answer;
if (answer == 8) {
std::cout << "You are correct!";
break;
}
else {
std::cout << "Wrong answer! Try again";
}
}
}

I need help on this C++ yes/no problem while using logical operators

So the problem is: Write a program that prints the question "Do you wish to continue?" and reads the input. If the user input is "Y", "Yes", "YES", then print out "Continuing". If the user input is "N" or "No", "NO" then print out "Quit". Otherwise, print "Bad Input". Use logical operators.
So far this is all the code that I have written. I know that it is not complete, and I do not know what else I need to add to the code.
#include <iostream>
using namespace std;
int main() {
char response;
cout << "Do you wish to continue?" ;
cin >> response;
if (response == 'Y'){
cout << "Continuing";
}
else if (response == 'N'){
cout << "Quit";
}
else if (response != 'N' || 'Y'){
cout << "Bad input";
}
return 0;
}
Update: so I edited my code and it is still giving me a bunch of errors. It's making me frustrated lol. Keep in mind I'm a beginner and we haven't learned loops yet. Sorry for the headache!
#include <iostream>
#include <string>
using namespace std;
int main() {
char response;
string help;
cout << "Do you wish to continue?" ;
cin >> response, help;
if (response == 'Y' || help == "Yes" || help == "YES"){
cout << "Continuing";
}
else if (response == 'N' || help == "No" || help == "NO"){
cout << "Quit";
}
else if (response != 'N' || response != 'Y' || help != "Yes" || help != "YES" || help != "No" || help != "NO"){
cout << "Bad input";
}
return 0;
}
First off I think this is a great start. Sounds like you are new to C++ so here are some suggestions:
1) Your response variable can only contain a character. I would suggest including string and changing the response to take a string from the user for 'Y', "Yes", etc.
2) I suggest wrapping your code in a while loop with an exit condition.
3) Each of your logic branches should include a return integer. This will give the program an exit condition if the logical conditions are met.
I know I haven't given you the answers fully. If you are truly stuck, reply back and we can walk through.
A simple way is to simply convert the user's answer to uppercase or lowercase. By doing this, you can simply use the lower case.
For your loop, you could for example use a "do..while".
#include <iostream>
#include <string>
using namespace std;
int main() {
int stop = 0;
string response;
//Continue until the user choose to stop.
do{
//-------------
// Execute your program
//-------------
cout << "Do you wish to continue? ";
cin >> response;
//-------------
//Convert to lower case
for (string::size_type i=0; i < response.length(); ++i){
response[i] = tolower(response[i]);
}
//-------------
//Check the answer of the user.
if (response.compare("y") == 0 || response.compare("yes") == 0){
cout << "Continuing \n";
}
else if (response.compare("n") == 0 || response.compare("no") == 0){
cout << "Quit \n";
stop = 1;
}
else{
cout << "Bad input \n";
}
}while(stop == 0);
return 0;
}
Like you said in the question, we care about Y,Yes,YES,N,No and NO. For anything else we need to print "Bad Input". Think about how you'd be storing these responses (hint: Sam Varshavchik's answer).
Once you've taken care of extracting user input, you'd want to check what the user actually entered and proceed accordingly. From your question it seems "if else" would do. You need to change the conditionals for your "if else ifs" because
you have 3 conditions for one type of response: Y, Yes and YES need one output - "continuing" while N, No and NO require a different output - "Quit" and for all others we print "Bad input". Think about what your conditionals should be and your if statement should look something like:
if (response == "Y" || response == "Yes" || response == "YES")
and then handle the case accordingly. You'd want to do the same for your No conditions and finally handle the case for all others. I'd suggest having your code like so:
if( conditionals for Yes){
//Code for Yes input
}
else if( conditionals for No){
//Code for No input
}
else{
//Code for all other inputs
}
It is tempting to give you the full answer but think about how your program needs to flow and proceed from there, you've almost got it!
If you have more questions post here and we'd be glad to help!

How to use if else statement

Today I want to test if a user types the word "yes" in console application, then the function will proceed, however, I am unable to do so. (I am a new person, sorry)
Any help on this?
I know when testing a variable like.. int x = 14, and if (a < 14) print something.. but instead of number I'd like to try with text.
Here is the source code:
int main()
{
char a = yes;
char b = no;
cout << "hi, press yes to start or no to cancel";
cin >> a;
if (a == yes)
{
cout << "Cool person";
}
else if(b == no)
{
cout << "not a cool person";
}
}
I keep getting "yes" is not defined in scope.
Any help would be appreciated. Thank You!
At a bare minimum, the following problems exist in your code:
Tokens yes and no are identifiers. If you wanted them to be characters, that would be 'yes' and 'no. Except that they're not characters since they're too long. So, they should probably be strings like "yes" and "no".
The b variable is totally useless here, you should have one variable for receiving information from the user and checking it against multiple possible values. It's also a good idea to choose meaningful variable names.
You aren't including the requisite headers, nor are you using the correct namespace for the std functions and types (either by explicitly prepending std:: to each, or with a using namespace std for them all).
With that in mind, try out the following program as a starting point for your further education:
#include <iostream>
#include <string>
int main() {
std::string userInput;
std::cout << "Hi, enter yes to start or no to cancel: ";
std::cin >> userInput; // probably better: std::getline(std::cin, userInput);
if (userInput == "yes") {
std::cout << "Cool person\n";
} else if (userInput == "no") {
std::cout << "Not a cool person\n";
} else {
std::cout << "Hey, can't you read? I said yes or no :-)\n";
}
}

Refine my code/program where did I go wrong?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int LordIronhead = 0;
char answer;
cout<<"Is Lord Ironhead present? Y/N.\n";
cin >> answer;
if (answer == 'Y')
{
LordIronhead=0;
}
else if (answer == 'N')
{
LordIronhead= LordIronhead+1;
}
cout<< ""<<LordIronhead<<"\n";
system("PAUSE");
return 0;
}
Every time I run the program and If I answer NO (N)
the result is always 0 instead of 1 (LordIronhead = LordIronhead + 1)
May I know where my error is?
Your code is fine in principle, but you might run into issues with the two-valued logic of 'answer' being checked against 'Y' and against 'N' with no fall-through case. I suspect you are running into EOL or case or character conversion issues, falling through both if's and thereby never changing the Lord.
For showing the problem, try an else statement:
else if (answer == 'N')
{
LordIronhead= LordIronhead+1;
} else {
std::cout << "Invalid answer '" << answer << "'" << std::endl;
}
Your code is correct but is sensitive to the case of user input (it treats user input of N and n differently). You'd remove a possible source of user confusion by converting the input to a known case before checking it. You can do this using either toupper or tolower
cin >> answer;
answer = toupper(answer);
I just tried this myself and found that if I answered N I got the expected answer (1). If I hit n, however, it came back as 0. Are you sure you're hitting N and not n?
Better using 1 and 0 instead of N and Y. Its more recognizable to the system

using user input such as YES and NO to control program flow in C++

I'm making a small program that uses a if else statement, but instead of using numbers to control the flow i want to be able to make the control work with with yes and no;
for example:
cout << "would you like to continue?" << endl;
cout << "\nYES or NO" << endl;
int input =0;
cin >> input;
string Yes = "YES";
string No = "NO";
if (input == no)
{
cout << "testone" << endl;
}
if (input == yes)
{
cout << "test two" << endl;
//the rest of the program goes here i guess?
}
else
{
cout << "you entered the wrong thing, start again" << endl;
//maybe some type of loop structure to go back
}
but I can't seem to get any variations of this to work, i could make the user type a 0 or 1 instead but that seems really stupid, i'd rather it be as natural as possible, users don't speak numbers do they?
also i need to be able to simply add more words, for example "no NO No noo no n" all would have to mean no
hopefully that makes some sense
also i would love to make this using a window but i've only learned basic c++ so far not even that and i cant find any good resources online about basic windows programming.
You're not reading in a string, you're reading in an int.
Try this:
string input;
instead of
int input = 0;
Also, C++ is case-sensitive, so you can't define a variable called Yes and then try to use it as yes. They need to be in the same case.
btw, your second if statement should be an else if, otherwise if you type in "NO" then it will still go into that last else block.
First of all, input must be std::string, not int.
Also, you've written yes and no wrong:
v
if (input == No)
// ..
// v
else if (input == Yes)
^^^^
If you want your program to work with "no no no ..", you could use std::string::find:
if( std::string::npos != input.find( "no" ) )
// ..
The same with "Yes".
Also, you could do this to be almost case-insensitive - transform the input to upper-case letters (or lower, whatever ), and then use find.This way, yEs will be still a valid answer.
bool yesno(char const* prompt, bool default_yes=true) {
using namespace std;
if (prompt && cin.tie()) {
*cin.tie() << prompt << (default_yes ? " [Yn] " : " [yN] ");
}
string line;
if (!getline(cin, line)) {
throw std::runtime_error("yesno: unexpected input error");
}
else if (line.size() == 0) {
return default_yes;
}
else {
return line[0] == 'Y' || line[0] == 'y';
}
}
string input;
cin >> input;
if (input == "yes"){
}
else if (input == "no"{
}
else {
//blah
}