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...
Related
This question already has answers here:
Read file line by line using ifstream in C++
(8 answers)
Closed 1 year ago.
I am trying to get the user to key in data and store them inside a vector so when -1 is being entered it will break the entire loop and start displaying the vector. However it is currently not working even if -1 has been entered the loop will still continue to go on.
void cargo::addCargo(vector<cargo> &userCargo)
{
fstream file;
file.open("cargo.txt", ios::out | ios::app);
int i = 0;
bool checker = true;
cargo newCargo;
while (checker == true)
{
cout << "Enter id" << endl;
if (cin.peek() == '-1')
{
checker = false;
cout << "Hello";
}
else
{
cin >> idCon;
newCargo.setId(idCon);
}
cout << "Enter Destination Country" << endl;
if (cin.peek() == '-1')
{
checker = false;
}
else
{
cin >> destCountryCon;
newCargo.setDestCountry(destCountryCon);
}
cout << "Enter Time" << endl;
if (cin.peek() == '-1')
{
checker = false;
}
else
{
cin >> timeCon;
newCargo.setTime(timeCon);
newCargo.setIndex(i + 1);
userCargo.push_back(newCargo);
}
cout << endl;
i++;
}
//loop to display the entire vector
displayCargo(userCargo);
}
You are code is not self-contained so I can't fix it for you. The pragmatic answer is break or continue with a flag like checker. peek() looks at the next character and when the user enters "-1" it will return '-' and not the multi-character constant '-1'. Alternative, user can press ctrl-d to trigger eof. If you want to use "-1" (who came up with that terrible ux?), read that as a string or int.
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.
This question already has answers here:
cin input (input is an int) when I input a letter, instead of printing back incorrect once, it prints correct once then inc for the rest of the loop
(2 answers)
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 4 years ago.
I've been coding in C++ for all of a few days, so please talk to me like I'm a baby. With that out of the way,
I've made a short algorithm that asks a set of questions (to be answered 0 for no and 1 for yes) and stores the user's answer as an integer. Everything works as expected as long as the user only inputs integers (or, in one case, a string with no spaces).
But if the input doesn't match the variable type, the program immediately outputs this infinite loop that appears later in the program. That loop is supposed to print a question, wait for input, and then ask again if the answer isn't '1', but in the failure state it just prints the question without end. I can't see any reason why the previous questions would be connected to this. It doesn't happen on the questions that come after it, if that's a clue.
Here's a pared-down version of my code with, I hope, all the important information intact:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int answer1;
string answer1C;
int answer2;
int answer2B;
int score;
score = 0;
cout << "Question 1" << endl;
cin >> answer1;
if (answer1 == 1)
{
++score;
//some other questions go here
cout << "Question 1C" << endl;
cin >> answer1C;
if (answer1C.size() == 6)
{
++score;
}
}
cout << "Question 2" << endl;
cin >> answer2;
if (answer2 == 0)
{
cout << "Question 2B" << endl;
cin >> answer2B;
if (answer2B == 0)
{
--score;
}
while (answer2B != 1) //Here is the infinite loop.
{
cout << "Question 2B" << endl;
cin >> answer2B;
}
}
cout << "Question 3" << endl;
//and so on
return 0;
}
I would love to have it accept any input and only perform the ensuing steps if it happens to meet the specified conditions: for instance, in question 1.2, it only awards a point if the answer is a string of length 6, and otherwise does nothing; or in question 2.1, it repeats the question for any input that isn't '1', and moves on if it is.
But in any case whatsoever, I need it to do something else when it fails. Please help me figure out why this is happening. Thank you.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
How best to parse the following string in c++:
the input is a string, for example:
(someString1 45)(someString2 2432)(anotherString 55) // .... etc.
of course we are interested with the string-name and value..
our goal is to save the string and value in a map.
is there a automatic way to get the string inside the brackets ?
thank you,
A simple solution if your strings don't contain whitespace:
#include <iostream>
#include <string>
int main()
{
char c1, c2;
int n;
std::string s;
while (std::cin >> c1 >> s >> n >> c2 && c1 == '(' && c2 == ')')
{
std::cout << "Parse item: s = '" << s << "', number = " << n << "\n";
}
}
This method only works on correct input and has no way of recovering mid-way. If you need that, you can build something somewhat more elaborate using getline with ) as the separator.
The following will do the trick:
string some; int n;
string s = "(someString1 45)(someString2 2432)(anotherString 55)";
stringstream sst(s); // to parse the string
while (sst.get() == '(' && sst >> some >> n && sst.get()==')') {
cout << some << "," << n << endl;
}
This loop will not try to read some string and n if the open brace is not present.
A slight change could even allow to safely parse further input string if you'd expect something to follow the list of entries between braces:
string s = "(someString1 45)(someString2 2432)(anotherString 55)thats the rest";
...
while (sst.get() == '(') { // open brace to process
if (sst >> some >> n && sst.get() == ')')
cout << some << "," << n << endl; // succesful parse of elements
else {
cout << "Wrong format !!\n"; // something failed
if (!sst.fail()) sst.setf(ios::failbit); // case of missing closing brace
}
}
if (sst) { // if nothing failed, we are here because open brace was missing and there is still input
sst.unget(); // ready to parse the rest, including the char that was checked to be a brace
string rest;
getline(sst, rest);
cout << "The braces are followed by: " << rest << endl;
}
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.