I want the user to also put a lowercase y into the system. How can I make it recognise it?
I apologise in advance if this question seems fairly basic, I'm still new to programming.
Scanner end = new Scanner(System.in);
System.out.println("Do you want to quit the program? " +
"Y - Yes/N - No");
char endchar;
endchar = endenext().charAt(0);
if (end == 'Y') {
break;
}
You can simply add one more condition end == 'y' with OR operator.
example: if (end == 'Y' || end == 'y')
Scanner end = new Scanner(System.in);
System.out.println("Do you want to quit the program? " +
"Y - Yes/N - No");
char endchar;
endchar = endenext().charAt(0);
if (end == 'Y' || end == 'y') {
break;
}
You can use the Character.toUpperCase() function to convert the user input to an upper case letter. That way the capitalisation won't matter.
import java.lang.*;
...
Scanner end = new Scanner(System.in);
System.out.println("Do you want to quit the program? " + "Y - Yes/N - No");
char endchar;
endchar = Character.toUpperCase(endenext().charAt(0));
if (end == 'Y') {
break;
}
Related
I'm trying to code a blackjack game and everything is going smoothly so far but for this bit. No matter what I input into hitStand it always goes to the first if statement and "hits". I would like for if "h" is inputted it "Hits" and if "s" is inputted it "Stands" and, if there is an invalid input, it will tell the user to try again.
I'm still fairly new to C++, so some help would be appreciated.
while (repeat == 0)
{
char hitStand;
cout << "Would you like to HIT or STAND [H/S]";
cin >> hitStand;
if (hitStand = "H" || "h")
{
PcardNew = rand() % 13 + 1;
cout << endl;
cout << "Your new card is: " << PcardNew << endl;
if (PcardNew > 10)
{
PcardNew = 10;
}
playerTotal = playerTotal + PcardNew;
cout << "Your new total is: " << playerTotal << endl;
}
else if (hitStand = "S" || "s")
{
break;
}
else
{
cout << "Please enter a valid imput [H/S]" << endl;
}
}
There are (at least) three errors in the single if (hitStand = "H" || "h") line!
First, the = operator is an assignment, not a comparison; to test for the equality of two operands, you need the == operator.
Second, the "H" and "h" constants are string literals - that is, multi-character, null-terminated strings of characters. Use single quotes for single characters (thus, 'H' and 'h').
Third, you can't compare one object with two others like that with a logical or (||) operator. You need to make two separate comparisons and then or the results of each:
So, use this:
if (hitStand == 'H' || hitStand == 'h')
{
//...
And similarly for your second test:
else if (hitStand == 'S' || hitStand == 's')
{
//...
That is because your condition in if statement is always true. Since "h" is in or (||).
Instead use:
if (hitStand == 'H' || hitStand == 'h')
and
else if (hitStand == 'S' || hitStand =='s')
I'm brand new into C++. I would like to know, why my code is not working.
I've got string called Response.
If the response begins with y/Y it should proceed. However I would like to proceed when the user types " y"/" Y" (the white space) as well.
Here is my code.
Thanks in advance!
bool AskToPlayAgain()
{
std::cout << "Would you like to play again? Yes/N";
std::string Response = "";
std::getline(std::cin, Response);
return (Response[0] == 'y') || (Response[0] == 'Y' +) ||(Response[0] == ' y' +) (Response[0] == ' Y' +);
std::cout << std::endl;
}
With Response[0] you access the first character of the string. You can compare that, as you do, with a character constant, such as 'y'. However, if you want to allow the leading space, this is no longer a single character, so your comparison Response[0] == ' y' cannot work.
Here is a version which allows as many space characters as needed, and then y or Y (C++11 version):
for (auto c:Response)
if (c!=' ')
return (c=='y') || (c=='Y');
//string is only spaces
return false;
You can traverse string Response and ignore white spaces(I am considering Tabs and Spaces in this case) while traversing.
If first character is non white space then you can break the loop I am using flag yes in this case.
bool AskToPlayAgain()
{
std::cout << "Would you like to play again? Yes/N";
auto Response="";
std::getline(std::cin, Response);
auto yes = false;
auto itr = Response.begin();
while(itr != Response.end())
{
if(*itr != ' ' && *itr !='\t')
{
yes = (*itr == 'y' || *itr =='Y') ;
break;
}
++itr;
}
return yes;
}
You can remove the spaces from the response and check with only 'Y'/'y'.
bool AskToPlayAgain()
{
std::cout << "Would you like to play again? Yes/N";
std::string Response = "";
std::getline(std::cin, Response);
Response.erase(remove(Response.begin(), Response.end(), ' '), Response.end());
return (Response[0] == 'y') || (Response[0] == 'Y');
}
Use a loop to check each of your character inside the input string...
For example, like this, usage of the usual loop which can be used in all versions of C++ (You can use the range based for loop like in the above answer...):
bool ask_to_play_again(std::string Response)
{
for (auto i = 0; i < Response.size(); i++)
if (!isspace(Response[i])) // Is not a whitespace character
return tolower(Response[i]) == 'y';
return false; // If the user enters invalid input, close the game anyway...
}
Kind regards,
Ruks.
Maybe you can use std::find function to resolve the problem.
bool AskToPlayAgain()
{
std::cout << "Would you like to play again? Yes/N";
std::string Response = "";
std::getline(std::cin, Response);
auto pos1 = Response.find("Y");
auto pos2 = Response.find("y");
if (pos1 != std::string::npos || pos2 != std::string::npos)
return true;
return false;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
When my program gets to the while(!looking) loop for the first time, it performs the task, but afterwards it doesn't continue on with taking the words and translating them. Need some help on figuring out why it doesn't run through.
while (cin.good()){
getline(cin, lines);
while (!looking) {
spot = lines.find(" ");
if (spot == -1){
looking = true;
spot = lines.length( );
}
line = lines.substr(0, spot);
TP1stLetter(line);
if (!looking)
lines = lines.substr(spot + 1, lines.length( ) - spot + 1);
}
cout << endl;
//while( cin.good() ) {
//getline (cin, line);
//for(x = 0; x < line.size(); x++) {
//char letter = line[x];
//if (letter == 'a' || letter == 'e' || letter == 'i'
// || letter == 'o' || letter == 'u'){
//cout << letter;
//}
//}
}
}
Just add one line of code after the cout statement as follow:
if (mode == TOPIG) {
cout << "TOPIG MODE" << endl;
while (cin.good()){
getline(cin, lines);
while (!looking) {
spot = lines.find(" ");
if (spot == -1){
looking = true;
spot = lines.length( );
}
line = lines.substr(0, spot);
TP1stLetter(line);
if (!looking)
lines = lines.substr(spot + 1, lines.length( ) - spot + 1);
}
cout << endl;
looking = false;
//while( cin.good() ) {
//getline (cin, line);
//for(x = 0; x < line.size(); x++) {
//char letter = line[x];
//if (letter == 'a' || letter == 'e' || letter == 'i'
// || letter == 'o' || letter == 'u'){
//cout << letter;
//}
//}
}
}
2 things I can think of, hope it helps
- Should you be setting looking = false at any point in your while(!looking) loop?
- Are you adding quote around your argument string in your command line
like this
YourExe.Exe these words are five arguments
But instead you need quotes to make a string
YourExe.Exe "this is one argument"
I'm currently making a login form for my project, but I can't move on on this one. I want my program to delete a character(in password) when I'm pressing the backspace button, but the program is not reading it.
Here's my code
string username, password, power;
char ast=' ';
int aste = 0, accessLevel;
ofstream addAcc;
addAcc.open("Accounts.txt");
cout<<"Username: ";cin.ignore();getline(cin, username);
cout<<"Password: ";
do
{
ast = getch();
if (ast == 13 || ast == ' ' )
{
break;
}
if(ast==8 || password!="")
{
cout<<"\b \b";
password.erase(password.size()-1);
}
cout<<"*";
password+=ast;
aste ++;
}while(ast!=13 || ast!=' ');
do
{
cout<<"Enter Access Level(0-1): ";cin>>accessLevel;
switch(accessLevel)
{
case 0:
{
power = "Cashier";
break;
}
case 1:
{
power = "Manager";
break;
}
default:
cout<<"Invalid access level."<<endl;
}
}while(accessLevel>1||accessLevel<0);
Thank you for those who will help.
On some platforms getch() will return the DEL character (ascii 127) when you hit BACKSPACE. So change your line
if(ast==8 || password!="")
to
if((ast==8 || ast==127) && !password.empty())
You probably don't want to erase a character everytime that password is not an empty string either, so I removed || password!="" from the condition too. Instead you want to erase one character only if the password is not empty. So you need an && instead of an ||.
Also note, that you're adding the character returned by getch() unconditionally. So if the user enters BACKSPACE, you erase the last character, but append BACKSPACE to the password. So you should only append the character returned by getch() if it was not a BACKSPACE (or DEL).
Thus your code might look like this:
if((ast==8 || ast==127) && !password.empty())
{
cout<<"\b \b";
password.erase(password.size()-1);
aste--;
}
else
{
password+=ast;
cout<<"*";
aste++;
}
do
{
c = _getch();
if (c == 13 || c == ' ') // checking ascii key 13 pressed or no
{
break;
}
if (c == 8 || c == 127)
{
if (Password.size() != 0){
cout << "\b \b";
Password.erase(Password.size() - 1);
StarNum--;
}
}
else {
Password += c;
cout << "*";
StarNum++;
}
} while (c != 13 || c != ' ');
Use
#include <conio.h>
and
ch = _getch();
instead ch = getch();
and also change the condition like this
if(ch == 8)
{
password.erase(password.size()-1);
aste--;
}else
{
password +=ch;
aste++;
}
I'm working on a project from class and it's a text analysis project. We're supposed to load a document into the program and basically read data from it. Ex: (word count, sentence count, etc.). For some reason, my first function isn't working correctly: my loadDocument function is supposed to load the document into the program.
Here is the code in main to call that function:
case 1: // Load Document
{
string inputLoc;
cout << "Please input the document name:" << endl;
cin >> docName;
myDocs[docCount].setName(docName);
myDocs[docCount].id = docCount;
cout << "Input Location: " << endl;
cin >> inputLoc;
myDocs[docCount].loadDocument(inputLoc);
docCount++;
break;
}
I have docName initialized outside of the case - before it.
Here is my loadDocument in side my Document class:
void Document::loadDocument(string name)
{
ifstream myFile(name);
int numOflines = 0;
string theLine;
char words;
while (myFile.get(words))
{
switch (words)
{
case '.':
numOflines++;
break;
case '?':
numOflines++;
break;
case '!':
numOflines++;
break;
}
}
lineCount = numOflines;
setLineCt(numOflines);
arr = new Line[lineCount];
myFile.close();
char theChar;
ifstream myFile2(name);
int key = 0;
if (myFile2.is_open())
{
for (id = 0; id < lineCount; id++)
{
while (theChar != '.' || theChar != '!' || theChar != '?')
{
myFile2 >> noskipws >> theChar;
theLine[key] = theChar;
key++;
}
myFile2 >> theChar;
arr[id].setStr(theLine);
}
}
}
I just wanted to know if my loadDocument has any evident bugs? For some reason, it's not actually loading a document into the program. For the input location, I typed in the exact file location of a text file that I want to input. For ex: C:\Users\Documents------. After I input that, my program just goes into an infinite loop.
Is my loadDocument doing what it's supposed to do? It's supposed to open a document and extract the number of sentences from it as well as number of words.
Also, am I testing it correctly by typing in that file location like that? I'm new to file input/output sorry.
Your while() loop is incorrect:
while (theChar != '.' || theChar != '!' || theChar != '?')
|| is not the right conditional operator here. If one condition is false, the two others will be true, thus leading to the infinite loop. You have to use &&:
while (theChar != '.' && theChar != '!' && theChar != '?')