C++ Check user's first name is not too short [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a function (below) that checks the user's first name for invalid characters and it works fine.
while(run)
{
size_t positionFirstName = userFirstName.find_first_of(invalidCharacter, 0, sizeof(invalidCharacter));
if (positionFirstName != string::npos)
{
cout << "Please only use letters. Please re-enter your first name." << endl;
cin >> userFirstName;
}
else
{
run = false;
}
}
I also want to check that the user's first name is not shorter than 3 characters.
I have tried a few times, and can get the program to run the first function, but if I put in another function to check name length, it seems to skip it. Any ideas?

Here's a slightly adjusted way to do it:
cout << "Please enter your first name." << endl;
while( cin >> userFirstName )
{
size_t positionFirstName = userFirstName.find_first_of(invalidCharacter, 0, sizeof(invalidCharacter));
if (positionFirstName != string::npos)
{
cout << "Please only use letters.";
}
else if( userFirstName.size() < 3 )
{
cout << "Name must be at least 3 characters long."
}
else {
break;
}
cout << " Please re-enter your first name." << endl;
}
Note that I've avoided repetition, but printing only the errors and handling the input in one place.

Related

Loop not accepting lowercase even with toupper (C++) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Currently, I want my code to accept lowercase or uppercase a, b, c, or u as a valid entry from the user. However, anytime I enter the characters as lowercase, they respond with the error message and continue the loop until it is put in uppercase. I am new to C++, so I might be using toupper wrong.
#include <iostream>
using namespace std;
int main()
{
bool custGBTypeValid = false;
bool custPlnTypeValid = false;
char custPlanType = toupper('Z');
int custUsedData = 1;
cout << "Hello, welcome to AT&T wireless. We're here to help you decide if your current plan is what's right for you." << endl;
cout << "Here are our plans:" << endl;
cout << "Plan A: For $25 per month 0GB are provided. Data is $10 per GB." << endl;
cout << "Plan B: For $45 per month 2GB are provided." << endl;
cout << "Plan C: For $80 per month 6GB are provided." << endl;
cout << "Plan Unlimited: Unlimited data for $100 per month." << endl;
while (custPlnTypeValid == false)
{
cout << "What type of plan are you on? (Please answer with A, B, C, or U): ";
cin >> custPlanType;
if (custPlanType == toupper('A') || custPlanType == toupper('B') || custPlanType == toupper('C') || custPlanType == toupper('U'))
custPlnTypeValid = true;
else
cout << "ERROR: Incorrect data type entered." << endl;
}
}
How would I get it to accept lowercase too? I have also tried changing each in the if statement to custPlanType == toupper('a') etc. and toupper(custPlanType == 'A') but this doesn't work either. The latter works if the characters within the code are lowercase, but then refuses to work with uppercase characters.
It should be:
if (toupper(custPlanType) == 'A' ....)

Why won't my "main()" function call a void function? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm working on a program to aid me in world-building that randomly generates a settlement (hamlet, village, town, city) based on a nation (German, Latin, Eastern) that the user chooses. Unfortunately, my code halts right at the "main()" function as it won't call the "settlementCreation()" void function I created.
I've tried moving the function I want to call above the "main()" function, or my usual method of creating the function above, defining it's contents below, but neither of these are working. I can't figure out any other solutions with my limited experience coding C++.
Main() Function:
int main() {
char tempChoice{};
bool isMakingSettlement = true;
while (isMakingSettlement = true) {
cout << "Create a settlement? (y/n): ";
cin >> tempChoice;
cout << "\n\n";
if (tempChoice == 'y') {
settlementCreation();
} else {
isMakingSettlement = false;
}
}
return 0;
}
settlementCreation() Function:
void settlementCreation() {
int tempType{};
int tempNation{};
bool isTypeValid = false;
bool isNationValid = false;
while (isTypeValid = false) {
cout << "What type of settlement would you like to create?:";
cout << "\n 1. Hamlet";
cout << "\n 2. Village";
cout << "\n 3. Town";
cout << "\n 4. City\n";
cin >> tempType;
if (tempType >= 1 && tempType <= 4) {
isTypeValid = true;
} else {
cout << " is an invalid choice, please select a valid choice.";
}
cout << "\n\n";
}
while (isNationValid = false) {
cout << "What nation would you like your settlement to be in?: ";
cout << "\n 1. Latin";
cout << "\n 2. German";
cout << "\n 3. Eastern\n";
cin >> tempNation;
if (tempNation >= 1 && tempNation <= 3) {
isNationValid = true;
} else {
cout << " is an invalid choice, please select a valid choice.";
}
cout << "\n\n";
}
Settlement objSettlement(tempType,tempNation);
}
So the program is supposed to allow the user to choose a nation and a settlement type before redirecting to the Settlement object constructor to create the objSettlement instance of the object.
The usual outcome however, is just an infinite loop of:
"Create a settlement? (y/n): "
With no responses I've tried closing the program or going to the "settlementCreation()" function.
while (isMakingSettlement = true) {
This does not check if isMakingSettlement is true. It sets isMakingSettlement to true! This means the check in the while loop always sees true, so never stops going round.
Use while (isMakingSettlement == true).
(Or while (isMakingSettlement), or while (true == isMakingSettlement); all are fine, it's a stylistic choice, though the last would have helped you catch this bug!).
Similarly for all your other while loops.
Assuming you fix the above, your next problem will be here:
bool isTypeValid = false;
bool isNationValid = false;
while (isTypeValid == false) { // once corrected
// ... never get here!
while (isNationValid == false) { // once corrected
// ... never get here!
You always set those bools to false, so these loops are never executed.

cout won't print in function [closed]

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 5 years ago.
Improve this question
I'm pretty new to programming so this might be a question with an obvious answer for you guys and I'm really stumped, why doesn't cout work in the following function? I've included the iostream header so I'm assuming it has something to do with it being in the function?
int inputFileData(song musicLibrary[])
{
char discard = ' ';
int counter = 0, length = 0;
ifstream inData;
inData.open("songs.txt");
if (!inData)
{
cout << "Error: No input file found " << endl;
cout << "Program terminating..." << endl;
return 1;
}
while (!inData.eof())
{
inData.getline(musicLibrary[counter].title, ARRAY_CONST, ';');
inData.getline(musicLibrary[counter].artist, ARRAY_CONST, ';');
inData >> musicLibrary[counter].durationMinutes;
inData.get(discard);
inData >> musicLibrary[counter].durationSeconds;
inData.get(discard);
inData.getline(musicLibrary[counter].album, ARRAY_CONST, '\n');
length = strlen(musicLibrary[counter].album);
if (length = 0)
{
cout << length << endl; //This cout object doesn't work in this function
break;
}
else
counter++;
}
return counter;
}
The line if (length = 0) should be if (length == 0).
Elaborating Eli's answer:
if (length = 0)
Assigns the value 0 to length and then evaluates the expression. Since the expression returns 0 the condition evaluates to false and you don't enter the if clause.
Instead, use if (length == 0)

How I can validate letters in c ++ with Try-catch? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I would like to improve the code below. I would like to use try-catch statement to validate the input letters. An error message should be printed in case the user inputs an invalid letter.
I have two methods: showMenu and selectOperation.
The methods:
//Show Operations in menu
void showMenu()
{
cout << " Select an option: \n\n"
<< "1 = Register new customers \n"
<< "2 = Register new products \n"
<< "3 = Add Product Existence \n"
<< "4 = Register a new purchase \n"
<< "0 = Exit \n\n";
}
//Select an Operation from menu
int selectOperation()
{
int selectedOperation = 0;
do
{
showMenu();
cin >> selectedOperation;
if ((selectedOperation < 0) || (selectedOperation > 4))
{
cout << "\n You have selected an invalid option"
<< "...Try again \n";
system("pause");
system("cls");
}
} while ((selectedOperation < 0) || (selectedOperation > 4));
return selectedOperation;
}
How should I do this?
You usually don't want to get and handle exceptions for invalid input.
Using exceptions to control regular flow of a program is a well known design flaw/anti pattern.
The idiomatic way is to check the input streams state:
// is true for non integer input and numbers outside the valid range
while(!(cin>>selectedOperation)) {
// Cleanup the stream state
cin.clear();
std::string dummy;
cin >> dummy; // Consume the invalid input
cout << "Please input a number." << std::endl;
}
The exception variant looks like this (way more complicated and less concise IMO):
cin.exceptions(std::ifstream::failbit);
bool validInput;
do {
try {
validInput = true;
cin>>selectedOperation)
}
catch (std::ios_base::failure &fail) {
validInput = false;
// Cleanup the stream state
cin.clear();
std::string dummy;
cin >> dummy; // Consume the invalid input
cout << "Please input a number." << std::endl;
}
} while (!validInput);
You have to clear the input stream in any way from fail() state.
You could also do this with a if else if statement...

C++ How check characters in real time with _getch() [closed]

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
i need in my loop get character in realtime and check it by conditions. If user press whatever except enter, program works fine. Can anyone help me ? thanks !
while (read != '\n')
{
cout << "Enter character:\n";
read = _getwch();
if (read == '\n') {
cout << "You pressed : ENTER\n";
}
else {
cout << "Your character is: \"" << read << "\"\n\n";
read = '\0';
}
}
include
using namespace std;
int main()
{
cout << "Press the ENTER key";
if (cin.get() == '\n')
{
cout << "Good job.\n";
}
else
{
cout << "I meant ONLY the ENTER key... Oh well.\n";
}
return 0;
}
This code will help in detecting the ENTER key when pressed.
Hope this helps you.