Input Validation Infinite Loop C++ [duplicate] - c++

This question already has answers here:
Why would we call cin.clear() and cin.ignore() after reading input?
(4 answers)
Closed 2 years ago.
First off, I am very new to C++ (I literally started learning it 2 hours ago, so go easy on me)
This simple program is supposed to check whether or not the user input is a valid number between 0 and 101 and simply respond, valid or invalid.
#include <iostream>
int main() {
bool isValidNum = false;
do
{
std::cout << "How many samples were collected?\n";
int numOfSamples;
std::cin >> numOfSamples;
isValidNum = (numOfSamples > 0 && numOfSamples < 101);
if (isValidNum) {
std::cout << "valid\n";
}
else {
std::cout << "invalid\n";
}
} while (isValidNum == false);
}
It works. Except that if you put anything other than an integer it loops infinitely.
I may have over stretched myself by using a do/while loop whilst so unfamiliar with this language.
What is wrong with the condition flow? (I assume i'm just being incredibly smoothbrained and need some coffee)

#include <iostream>
#include <string>
using namespace std;
int main() {
bool isValidNum = false;
string input;
int numOfSamples;
std::cout << "How many samples were collected?\n";
do
{
getline(cin, input, '\n');
if (input == "")continue;
numOfSamples = atoi(input.c_str());
isValidNum = (numOfSamples > 0 && numOfSamples < 101);
if (isValidNum) {
std::cout << "valid\n";
}
else {
std::cout << "invalid\n";
}
} while (isValidNum == false);
}

Related

If/else statement not working correctly (C++, onlinegdb.com/online_c++_compiler) [duplicate]

This question already has answers here:
If statement always executing even when the condition is false?
(3 answers)
How to write an if statement with multiple || and && in C? [closed]
(2 answers)
Closed 11 months ago.
It has been months since I did anything on c++, I took a certificate course. I only learned the basics, and wanted to refresh myself. I am trying to make a simple RNG calculator. I am writing code to confirm the max and min entered by the user. However, the confirmation code is not doing the if else correct. No matter what char confirm is, it defaults to the first statement in the "if (confirm == 'Y' || 'y')" (It has been a while, please don't critisize my code too too much)
#include <iostream>
#include <string>
using namespace std;
int max ()
{
int max;
int restart = 1;
char confirm;
do
{
cout << "What is the maxium number you want to be able to generate?";
cin >> max;
cout << "Let me confirm. Your maximum number is " << max << ", is this correct? (Y/N)";
cin >> confirm;
if (confirm == 'Y' || 'y') {
cout << "y";
return max;
}
else
{
}
}while (restart == 1);
}
int main ()
{
int maximum = max();
cout << maximum;
return 0;
}

Why isn't the program outputting true regardless of case?

My assignments requires me to keep accepting input from the user and output whether or not it is a palindrome until the word DONE is inputed.
Also, words like Bob must have an output of true because we must disregard case (upper/lower.)
This is my first time using C++.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string wordInput;
while (wordInput != "DONE")
{
cout << "Please enter a word: ";
cin >> wordInput;
int wordLength = wordInput.length();
int wordHalf = (wordLength / 2);
bool flag = false;
for (int i = 0; i <wordHalf; i++)
{
if (tolower((wordInput[i]) == tolower(wordInput[wordLength-1-i])))
{
flag = true;
}
else
{
flag = false;
break;
}
}
if (flag == true)
{
cout << "true"<<endl;
}
else
{
cout << "false"<<endl;
}
}
return 0;
}
It might have something to do with 'wordInput' being declared twice, once right before the while loop and once within it. It is mixing up what the while loops condition is looking at.
Your issue with words not being correctly identified comes from this line:
if(tolower((wordInput[i]) == tolower(wordInput[wordLength-1-i])))
If you look carefully, you set the parentheses incorrectly. Try this instead:
if(tolower(wordInput[i]) == tolower(wordInput[wordLength-1-i]))

Why can't compare two strings in if condition? [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 7 years ago.
Improve this question
Why can't compare two strings in if condition?
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string sexo[20], feminino;
feminino = "f";
for (int i = 0; i < 3; i++) {
do {
cout << endl << "enter your " << i + 1 << "sexo: ";
cin >> sexo[i];
if (strcmp(sexo[i], feminino)==0){ // problem in here
cout << "that's ok" << endl;
}
} while (nome[i] == "0");
}
return 0;
}
You've been reading "tutorials" for C, or "tutorials" for C++ that actually teach you a terrible and outdated mix of C and C++.
The function strcmp is from the C Standard Library, and does not operate on the C++ std::string type.
To compare two std::strings, simply write:
if (sexo[i] == feminino) {
I find it hard to believe that your C++ book does not teach you this.
These are a few correct ways to compare these strings (in reverse order of preference)
if (strcmp(sexo[i].c_str(), feminino.c_str()) == 0) {
if (sexo[i].compare(feminino)) == 0) {
if (sexo[i] == feminino) {
You are using the wrong compare function. What you are using works with char * (it is used in C) but here you have std::string so you have to use std::string::compare()
Change your code to this:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string sexo[20], feminino; // problem in here
feminino = "f";
for (int i = 0; i < 3; i++) {
do {
cout << endl << "enter your " << i + 1 << "sexo: ";
cin >> sexo[i];
if (sexo[i].compare(feminito) == 0){
cout << "that's ok" << endl;
}
} while (nome[i] == "0");
}
return 0;
Note that you can also use sexo[i] == feminito as you have relational operators for std::string (see here for examples)

While-loop breaks, and I don't know the reason why

I was writing a code for a counter. If I give 'a' as input, it should +1 the counter and show it on the screen. But when I do it, it shows 1 on the screen and the program ends. I want it to run until and unless i give some other character as input. What's the mistake I am making?
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Counter = 0;
char t;
while(true)
{
t = cin.get();
if(t == 97)
{
Counter = Counter + 1;
}
else
break;
system("cls");
cout << Counter;
}
return 0;
}
The issue is when you are entering your 'a', you are probably hitting Enter as well, which is interpreted as another char. That second char is definitely not a, so your program breaks. This can be verified by just outputting what you read:
for (;;) {
std::cout << '?';
char t = std::cin.get();
std::cout << (int)t << '\n';
if (t != 'a') break;
}
std::cout << "done\n";
Which, when run, prints:
?a
97 // this is 'a'
?10 // this is '\n', note the additional ?
done
The simplest fix would be to use the input stream operator on cin, which would discard whitespace in the input (whereas get() does not):
char t;
for (;;) {
std::cout << '?';
std::cin >> t;
std::cout << (int)t << '\n';
if (t != 'a') break;
}
std::cout << "done\n";
Which, when run, produces:
?a
97
?b
98
done
which is what you'd intended.
Try this:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Counter = 0;
char t;
while(true)
{
t = cin.get();
if(t == 97)
{
Counter = Counter + 1;
}
// else
// break;
system("cls");
cout << Counter;
}
//system("pause");
return 0;
}
Your else break; is the reason why you're closing after any interation. Basically after any iteration, it will break because due to any non-a input. However, running the code above, you will see the counter increment at every a input given and it will not break.
This will give you the basic operation you're looking for which is increment the counter based on input a, otherwise do nothing.
Edit: The above code will buffer your input and read it all, so if you have 5 a's like the following aaaaa, it will read it and output 5 for the counter.
If you want to break out of the loop, i suggest this:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Counter = 0;
char t;
while(true)
{
cin >> t;
// t = cin.get();
if(t == 97)
{
Counter = Counter + 1;
}
else
break;
system("cls");
cout << Counter;
}
//system("pause");
return 0;
}
I tested it and it works. Seems to be with how cin.get() reads the buffered input from the console (i think). Not too sure on the specifics, but cin >> t does the trick.
Edit 2: Did some reading and i think cin.get() will consume the next character after your input, but in this case it is a newspace \n, which is why it will always break in your original code.

getline() gets bypassed without proper user input the first time [duplicate]

This question already has answers here:
getline not asking for input? [duplicate]
(3 answers)
Closed 9 years ago.
cout << "Type in your third message below:\n";
getline(cin, msgth);
if (msgth.length() > 0 && msgth.length() < 500) {}
else
{
system("cls");
cout << "Your message has to be between 1 and 500 characters long...";
goto prot;
}
So, whenever I get to this piece of code, it's like it automatically presses return, and "skips" the getline() function (AKA, goes to the prot label). The same thing happens further up for some reason. However, after a bit of experimenting, I've found out that when using this:
input:
if (special == 0)
{
cout << "Choose your input message below:\n";
getline(cin, inp);
if (inp.length() > 0 && inp.length() < 500) {}
else
{
system("cls");
cout << "Your message needs to be between 1 and 500 characters long\n";
goto input;
}
}
It does work the second time (with other words, after going to the input label). The difference between these two codes is that the first one has to bypass a std::cin code before getting back to getline(), while the other one doesn't.
A solution and some explaination would be gladly appreciated.
The following works for me:
#include <iostream>
#include <string>
int main() {
std::string str;
start:
std::cout << "prompt:\n";
std::getline(std::cin, str);
if (0 < str.length() && str.length() < 20) {}
else {
std::cout << "invalid.\n";
goto start;
}
std::cout << "input: \"" << str << "\"\n";
}
How is yours different from this?