"noskipws" works but doesn't stop in c++ - c++

I am trying to write a program that checks if a phrase is a palindrome or not, and in case nothing is entered or just whitespace, it should print out "empty".
At first, the user should type in the number of phrases that they are going to enter (e.g. 3), and then the phrases that are to be checked.
It works just fine, but when my first input is empty, it prints out "empty" again and again without asking for another phrase.
#include <iostream>
#include <string>
#include <iomanip>
#include <math.h>
using namespace std;
int main() {
int N;
int isPalindromeCounter=0;
int counter = 0;
string inputString;
cin >> N;
cout << "\n";
while (counter<N){
counter++;
cin.ignore(100, '\n');
cin >> noskipws >> inputString;
if (inputString.length()==0){
cout <<"empty\n";
continue;
}
int left = 0;
int right = inputString.length()-1;
if (inputString.length()>20){
cout <<"error\n";
continue;
}
bool isPalindrome = true;
while (left<right){
if (inputString[left] != inputString[right]){
isPalindrome = false;
cout << "no\n";
break;
}
left++;
right--;
}
if (isPalindrome){
cout << "yes\n";
isPalindromeCounter++;
}
}
double percentage = double(isPalindromeCounter)/double(counter)*100;
if (trunc(percentage) != percentage){
cout << setprecision(5) << percentage;
}
else {cout << percentage << ".000" ;}
return 0;
}
What am I doing wrong ?
I expected that it should print "empty" once, and then ask for another input, but it prints "empty" for all the inputs.

Related

How can I count alphabet characters efficiently?

I initialized an array of characters, to put all uppercase and lowercase alphabets.
#include <iostream>
using namespace std;
int main () {
char c;
int cnt = 0;
cout << "Enter 0 to view the results " << endl;
char arr[52] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
while (1) {
for (int i = 0; i < 100000000; i++)
{
cin >> c;
if (c == arr[i]){
cnt++;
}
else if (c == '0'){
break;
}
else{
cout << "Please enter only characters!" << endl;
}
}
if (c == '0')
break;
}
cout << cnt << endl;
return 0;
}
I know that this code is inefficient.
How to write this code without break;?
If there's a better way to do that without using array, please mention it.
OP's question is very unclear but what I have understood from the comments is OP trying to find a simpler/similar way of counting someone's input for lowercase/upperCase alphabets and keep doing so until the user enters in a 0, I looked online and i found a better way and did some adjustments, it is pretty straight forward, here it is below.
#include <algorithm>
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
int main()
{
string s = "TEST";
while(s != "0"){
cout << " Enter text: ";
getline(cin, s);
size_t count_alpha = count_if(s.begin(), s.end(),
[](unsigned char ch) { return isalpha(ch); });
cout << "Alphabets: " << ( count_alpha)<<endl ;
}
}

Error handling with c++

I need to do some error handling in c++ that corrects user input if it's a letter or a string. I need to use .at(), .length(), and atoi to handle this. I'm not sure how/where to implement those is the problem.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <time.h>
using namespace std;
int main() {
srand(time(0));
int number;
number = rand() % 50 + 1;
int guess;
int x;
for (x = 5; x > 0; x--) {
cout << "Guess my number, it's between 0-50. You have 5 guesses: ";
cin >> guess;
if (guess < number){
cout << "Your guess was too low" << endl;
}
else if (guess > number){
cout << "You guess was too high" << endl;
}
else {
cout << "You're exactly right!" << endl;
break;
}
} while (guess != number){
break;
}
return 0;
}
The best approach to input validation is to write a function that reads into a std::string, checks whatever is needed, and only returns a value when it passes the tests:
int get_value() {
std::string input;
int value = -1;
while (value < 0) {
std::cout << "Gimme a value: ";
std::getline(std::cin, input);
try {
value = std::stoi(input);
} catch(...) {
value = -1;
}
}
return value;
}

How to clear the previous input in c++?

'cause my program joins the previous input to my current input. I want to clear the previous input.
This is the code:
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <conio.h>
using namespace std;
int main()
{
int ini=1,an=1,ans=1, f=1;
int bb=2;
int hypin;
string a="a.) Hyperfactorial";
string b="b.) Superfactorial";
string c="c.) Primorials";
string d="Exit";
string e="a. Yes";
string ff="b. No";
string letter;
string ysno;
start:
cout<<"\n"<<"Factorial"<<"\n"<<a<<"\n"<<b<<"\n"<<c<<endl;
cout<<"\n"<<"Enter letter:"<<endl;
cin>>letter;
if (letter=="a"){
cout<<"\n"<<"Enter number (maximum input:7) : "<<endl;
cin>>hypin;
if(hypin>=8){
cout<<"\n"<<"Invalid input!"<<endl;
}else{
while (hypin>1){
ini=ini*(pow(hypin,hypin));
hypin--;
}
cout<<"\n"<<"The hyperfactorial is: "<<ini<<endl;}
cout<<"\n"<<"Do you want to test another factorial?"<<"\n"<<e<<"\n"<<ff<<endl;
cout<<"\n"<<"Answer: ";
cin>>ysno;
if(ysno=="a"){
goto start;
}
if(ysno=="b"){
cout<<"\n"<<"Press any key to exit"<<"\n"<<endl;
getch();
return 0;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
Try clearing the cin buffer using
std::cin.ignore(INT_MAX);
Edit: You have to #include <limits.h> to use INT_MAX
You don't need to clear any thing. infact you have some little bug in your code that not set the answer every time.
I try to write a simple code for you:
bool validInput = false ,continueFlag = true;
string opr, ysno;
int a , b, ans = 0;
while(continueFlag)
{
cout << "Choose operation: a. Multiply b. Add \n Enter letter: " << endl;
cin >> opr;
if (opr != "a" && opr != "b")
{
cout << "Invalid input!"<<endl;
continue; // it returns to "while(continueFlag)" line
}
cout << "Enter First Number: ";
cin >> a;
cout << "Enter Second Number: ";
cin >> b;
if (opr == "a")
{
ans = a * b;
}
else
{
ans = a + b;
}
cout << "Answer is : "<< ans << endl;
do
{
cout << "Do you want to test another factorial? a. Yes b. No" << endl;
cin >> ysno;
if (opr != "a" && opr != "b")
{
cout << "Invalid input!"<<endl;
continue; // it returns to "do" line
}
validInput = true;
if (ysno == "b")
{
continueFlag = false;
}
}while(!validInput);
}
try this might be helpful
cout << "\033[2J\033[1;1H";
I used this code and compiled with g++ its working and linux platfrom(ubuntu)
#include <cstdlib>
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int ini=1,an=1,ans=1, f=1;
int bb=2;
int hypin;
string a="a.) Hyperfactorial";
string b="b.) Superfactorial";
string c="c.) Primorials";
string d="Exit";
string e="a. Yes";
string ff="b. No";
string letter;
string ysno;
start:
cout<<"\n"<<"Factorial"<<"\n"<<a<<"\n"<<b<<"\n"<<c<<endl;
cout<<"\n"<<"Enter letter:"<<endl;
cin>>letter;
if (letter=="a"){
cout<<"\n"<<"Enter number (maximum input:7) : "<<endl;
cin>>hypin;
cout << "\033[2J\033[1;1H";
if(hypin>=8){
cout<<"\n"<<"Invalid input!"<<endl;
}else{
while (hypin>1){
ini=ini*(pow(hypin,hypin));
hypin--;
}
cout<<"\n"<<"The hyperfactorial is: "<<ini<<endl;}
cout<<"\n"<<"Do you want to test another factorial?"<<"\n"<<e<<"\n"<<ff<<endl;
cout<<"\n"<<"Answer: ";
cin>>ysno;
if(ysno=="a"){
goto start;
}
if(ysno=="b"){
cout<<"\n"<<"Press any key to exit"<<"\n"<<endl;
return 0;
} }
system("PAUSE");
return EXIT_SUCCESS;
}

char uninitialized, isnumber method unidentified,

I'm having errors in my code below,
This is my code:
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''";
char ch;
int i = 0;
while (Isnumber(ch)){ //here is the error
do{
ch = getchar();
int newnumber = 0;
cout << "element(" << i << ") = ";
cin >> newnumber;
numbers.push_back(newnumber);
} while (ch>0 || ch < 9);
}
getchar();
}
two errors,
it says that identifier is unknown,
and
it says variable char is uninitialazed local variable,
change this while (Isnumber(ch)){ into do-while loop.
do{
.....
}while (Isnumber(ch))
The error is because ch is declared and it is used before initialized.
Also include #include <stdio.h>; for getchar();
Better do it in one loop:
do {
ch = getchar();
int newnumber = 0;
cout << "element(" << i << ") = ";
cin >> newnumber;
numbers.push_back(newnumber);
} while (Isnumber(ch)); // should probably be isdigit(ch)
And before asking similar questions read this first (or buy a book).
Well I solved it using cin functions as below,
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''\n";
//char ch;
int counter = 0;
do{
int newnumber = 0;
cout << "element(" << counter << ") = ";
counter++;
cin >> newnumber;
numbers.push_back(newnumber);
if (cin.fail()){
cout << "entered numbers are:\n";
for (vector<int>::iterator i = numbers.begin(); i != numbers.end(); i++)
{
cout << *i;
if (i != numbers.end()-1)cout << " - ";
}
}
} while (cin.good());
getchar();
}
I removed one while loop.
and used cin.fail and cin.good to avoid using IsNumber. And it worked.

Do While loop breaks after incorrect input?

I am trying to have a loop continue to prompt the user for an option. When I get a string of characters instead of an int, the program loops indefinitely. I have tried setting the variable result to NULL, clearing the input stream, and have enclosed in try{}catch blocks (not in this example). Can anyone explain to me why this is?
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int menu(string question, vector<string> options)
{
int result;
cout << question << endl;
for(int i = 0; i < options.size(); i++)
{
cout << '[' << i << ']' << options[i] << endl;
}
bool ans = false;
do
{
cin >> result;
cin.ignore(1000, 10);
if (result < options.size() )
{
ans = true;
}
else
{
cout << "You must enter a valid option." << endl;
result = NULL;
ans = false;
}
}
while(!ans);
return result;
}
int main()
{
string menuQuestion = "Welcome to my game. What would you like to do?";
vector<string> mainMenu;
mainMenu.push_back("Play Game");
mainMenu.push_back("Load Game");
mainMenu.push_back("About");
mainMenu.push_back("Exit");
int result = menu(menuQuestion, mainMenu);
cout << "You entered: " << result << endl;
return 0;
}
It looks like there is a random element here, since result is not initialized.
In any case, test cin directly
if ( cin && result < options.size() )
and reset it upon invalid input so it will again perform I/O operations
result = 0; // inappropriate to initialize an integer with NULL
cin.clear(); // reset cin to work again
cin.ignore(1000, '\n'); // use \n instead of ASCII code