How to clear the previous input in c++? - 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;
}

Related

"noskipws" works but doesn't stop in 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.

Make this program display an error message if a negative number is entered, and prompt for a new positive number?

How can I make this program display an error message if a user enters a negative number, and then prompt for a new positive number? Since this is a decimal to hexadecimal calculator the user should not be able to enter a negative number.
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
int main()
{
bool play_again;
do
{
int dec_num, r;
string hexdec_num = "";
char hex[] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
cout << "\n\n Convert a decimal number to hexadecimal number:\n";
cout << "---------------------------------------------------\n";
cout << " Input a decimal number: ";
cin >> dec_num;
while (dec_num > 0)
{
r = dec_num % 16;
hexdec_num = hex[r] + hexdec_num;
dec_num = dec_num / 16;
}
cout << " The hexadecimal number is : " << hexdec_num << "\n";
while (true) // loop asking user
{
string user_input;
cout << "again? ('y', 'n'):" << endl;
cin >> user_input;
if (user_input == "y")
{
play_again = true;
break;
}
else if (user_input == "n")
{
play_again = false;
break;
}
else
{
cout << "Invalid Input" << endl;
}
}
} while (play_again);
}
You can solve this problem by adding an if statement after the cin >> dec_num; so you can check its value if it's under the 0 or no
add this line under the line cin >> dec_num;:
if (dec_num < 0)
{
//do whatever you want here
}

Cannot get my getchar() function to work how I want it to work, output is10 not 2 c++

I cannot figure out why my getchar() function is not working the way I want it to work. I am getting 10 not 2. Please take a look.
Main():
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int var, newvar;
cout << "enter a number:" << endl;
cin >> var;
newvar = getchar();
cout << newvar;
return 0;
}
Here is my output:
enter a number:
220
10
Ultimately though I need to be able to distinguish between a '+' '-' or letter or number.
This is maybe not the cleanest way to do it but you can get every char one by one :
#include <iostream>
using namespace std;
int main()
{
int var;
cout << "enter a number:" << endl;
cin >> var;
std::string str = to_string(var);
for(int i=0; i < str.length();++i)
cout << str.c_str()[i] << endl;
return 0;
}
If you enter for example: "250e5" it will get only 250 and skip the last 5.
Edit:
This is just a simple parser and does not do any logic.
If you want to make a calculator I would recommend you to look at what Stroustrup did in his book the c++ programming language.
int main()
{
string str;
cout << "enter a number:" << endl;
cin >> str;
for(int i=0; i < str.length();++i) {
char c = str.c_str()[i];
if(c >= '0' && c <= '9') {
int number = c - '0';
cout << number << endl;
}
else if(c == '+') {
// do what you want with +
cout << "got a +" << endl;
} else if(c == '-')
{
// do what you want with -
cout << "got a -" << endl;
}
}
return 0;
}

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;
}

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.