I was writing a simple calculator in c,whereby the user inputs two numbers and afterward choose the operation to apply on them.(Mul,Add,Div,Sub)The program works except it skips the part where its supposed to take user input for the operand.what am i doing wrong
#include<stdio.h>
#include<sstream>
#include<iostream>
#include<conio.h>
#include<string.h>
using std::cout;
using std::cin;
using namespace std;
int main() {
char Operative[100];
int a;
int b;
int c;
printf("Enter First Number\n");
scanf("%d",&a);
printf("Enter First Number\n");
scanf("%d",&b);
printf("\nPlease Enter Operation(M,A,D,S)");
gets(Operative);
//getline(cin,Operative);
if (Operative == "M")
{
c = a*b;
printf("Multiplication value is %d",c);
}
else if (Operative == "A")
{
c = a+b;
printf("Addition value is %d",c);
}
else if (Operative == "D")
{
c = a/b;
printf("Division value is %d",c);
}
else if (Operative == "S")
{
c = a-b;
printf("\nSubtraction value is %d",c);
}
}
Use strcmp to compare strings values. == compares pointers:
if (strcmp (Operative, "M") == 0) ...
You have to call cin.ignore() (after scanf, before gets) first, because there is still \0 in the buffer.
You can also use switch statement.
switch(operation){
case 'P':
result = a+b;
printf("%d + %d = %d", a,b,result);
.
.
.
Just code this in your int main() if you prefer to use printf and scanf you replace and everything will be ok.
do {
cout << "Option 1 <<endl;
cout << "Option 2 <<endl;
cout << "Option 3 <<endl;
cin >> x;
switch (x) {
case 1:
//Your operation here
break;
case 2:
//Your operation here
break;
case 3:
//Your operation here
break;
case 4:
exit(0);
break;
default:
cout << "Input a valid option" <<endl;
}
} while(x);
Related
I am providing the code that I converted to the C language and the converted code as well. The code works just as desired in C++ but I am unable to enter the value of the 'Operator' variable in the C language version.
This is the C++ code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
float num;
float num2;
char Operator;
char choice;
float result;
cout << "Select one of the following items:\n";
cout << "B) - Binary Mathematical Operations, such as addition and subtraction.\n";
cout << "U) - Unary Mathematical Operations, such as square root, and log.\n";
cout << "A) - Advances Mathematical Operations, using variables, arrays.\n";
cout << "V) – Define variables and assign them values.\n";
cout << "E) - Exit\n";
cin >> choice;
if (choice == 'U' || choice == 'u') {
cout << "Please enter the operation ( S (for square root) , L (for logarithm) , E (for exponential) , C (for ceil) , F (for floor) ):\n";
cin >> Operator;
rerun:
cout << "Enter a positive value.\n";
cin >> num;
if (num < 0) {
goto rerun;
}
else {
switch (Operator) {
case 'S':
result = sqrt(num);
break;
case 'L':
result = log(num);
break;
case 'E':
result = exp(num);
break;
case 'C':
result = ceil(num);
break;
case 'F':
result = floor(num);
break;
default:
result = 0;
break;
}
}
cout << fixed << setprecision(2) << result;
}
return 0;
}
This is the C language code:
#include <stdio.h>
#include <math.h>
int main()
{
double num;
char Operator;
char choice;
double result;
printf("Select one of the following items:\n");
printf("B) - Binary Mathematical Operations, such as addition and subtraction.\n");
printf("U) - Unary Mathematical Operations, such as square root, and log.\n");
printf("A) - Advances Mathematical Operations, using variables, arrays.\n");
printf("V) - Define variables and assign them values.\n");
printf("E) - Exit\n");
scanf("%c", &choice);
if (choice == 'U' || choice == 'u') {
printf("Please enter the operation ( S (for square root) , L (for logarithm) , E (for exponential) , C (for ceil) , F (for floor) ):\n");
scanf("%c", &Operator);
printf("Enter a positive value.\n");
scanf("%lf", &num);
switch (Operator) {
case 'S':
result = sqrt(num);
break;
case 'L':
result = log(num);
break;
case 'E':
result = exp(num);
break;
case 'C':
result = ceil(num);
break;
case 'F':
result = floor(num);
break;
default:
result = 0;
break;
}
printf("the answer is %lf", result);
}
return 0;
}
Both the codes are working except I am unable to input the value of the 'Operator' variable in the C version whereas it works great in C++.
Any help regarding this is truly appreciated.
Unlike the equivalent C++ code inputing a character using %c does not skip whitespace. To do that you should add a space before the %c, like this
scanf(" %c",&Operator); // skip whitespace then read a char
This code will work for you!.
Actually you should have better understanding of how buffered input works.
#include <stdio.h>
#include <math.h>
int main()
{
double num;
char Operator;
char choice;
double result;
printf("Select one of the following items:\n");
printf("B) - Binary Mathematical Operations, such as addition and subtraction.\n");
printf("U) - Unary Mathematical Operations, such as square root, and log.\n");
printf("A) - Advances Mathematical Operations, using variables, arrays.\n");
printf("V) - Define variables and assign them values.\n");
printf("E) - Exit\n");
scanf("%c", &choice);
char eat_line;
scanf("%c", &eat_line);
if (choice == 'U' || choice == 'u') {
printf("Please enter the operation ( S (for square root) , L (for logarithm) , E (for exponential) , C (for ceil) , F (for floor) ):\n");
scanf("%c", &Operator);
scanf("%c", &eat_line);
printf("Enter a positive value.\n");
scanf("%lf", &num);
switch (Operator) {
case 'S':
result = sqrt(num);
break;
case 'L':
result = log(num);
break;
case 'E':
result = exp(num);
break;
case 'C':
result = ceil(num);
break;
case 'F':
result = floor(num);
break;
default:
result = 0;
break;
}
printf("the answer is %lf", result);
}
return 0;
}
So this is my code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
long int iterFunc(int);
long int recurFunc(int);
int main() {
int n;
while(true){
try{
cout << "Enter: ";
if (!(cin >> n))
throw("Type Error");
if (n < 0)
throw n;
else
if (n == 0)
break;
cout << "Iterative: " << iterFunc(n) << endl;
cout << "Recursive: " << recurFunc(n) << endl;
}
catch(int n){
cout << "Error. Enter positive number." << endl;
}
catch(...){
cin.clear();
cin.ignore(100, '\n');
cout << "Error. Please enter a number" << endl;
}
}
cout << "Goodbye!";
return 0;
}
long int iterFunc(int n){
vector<long int> yVec = {1, 1, 1, 3, 5};
if (n <= 5)
return yVec[n - 1];
else
for(int i = 5;i < n; i++){
long int result = yVec[i - 1] + 3 * yVec[i- 5];
yVec.push_back(result);
}
return yVec.back();
}
long int recurFunc(int n){
switch (n) {
case 1:
case 2:
case 3:
return 1;
break;
case 4:
return 3;
break;
case 5:
return 5;
break;
default:
return recurFunc(n - 1) + 3 * recurFunc(n - 5);
break;
}
}`
The program shoud accept only one integer and return the y of the function using both iterative and recursive implemetations. Ex.: 30, 59, 433. How can I throw an error message if the user enters more then one integer, separated by space? Ex.: '3 45 32'.
I tried using if (cin.getline == ' ') throw("Error name") but the program still executes and return the y of the function for number in the input
Something like this works:
int main()
{
std::string str;
std::cout << "? : ";
std::getline(std::cin, str);
std::string::size_type pos(0);
int i = std::stoi(str, &pos);
if (pos != str.length())
return 1;
}
I found a part of my old code that might come in handy.
int val;
do
{
cin>>val;
if(!cin){ //you can add more conditions here
cin.clear();
cin.sync();
/* additional error handling */
}
else{
break; //input is correct - leaving loop
}
}while(true); //or here
Basically what !cin does is - it checks what type of value you actually want to write to, because it's needed anyway to figure out if data type is written to the correct type of our val. This means, that "30" or "433" etc. are integers (correct), "s" or "string" etc. are strings (or char*, correct me if I am wrong) (incorrect).
This also means, that "3 45 32" should be interpreted as string, which should result in another loop run.
Note: I didn't really test this code, so it might be completely wrong.
Edit: Okay now after some tests I realised this code needs some retweaking.
Firstly, "3 45 32" is not interpreted as string (now understandable). Instead, first number (before whitespace) is saved as an integer and all other numbers are stored in the buffer (next cin will be filled with it), which we can avoid using cin.clear() and cin.sync() once again.
The question is - is it okay for you to accept the first integer and ignore everything after the first whitespace? If not, you will have to save the input as string and extract whatever data you want from it.
I am leaving the original answer as is for simplicity of finding references in this edit.
scratching my head on this as it was working just fine earlier but when I went to add some other functions suddenly my program freaked out and I can not get it back to what it was.
class has me writing a rock/paper/scissors program to go up against a computer, any help with why the loop keeps terminating itself would be wonderful
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void RPSout(char);
int RPScomp();
int main() {
char choice;
int endit=0;
while (endit == 0)
{
cout << "\n\n\tReady to play Rock/Paper/Scissors against the computer??(please choose R/P/S)(Q to quit)\n";
cin >> choice;
RPSout(choice);
if (choice=='Q'||'q')
{endit=1;}
}
return 0;
}
void RPSout(char choose)
{
int RPS =0;
int comp=0;
switch (choose)
{
case 'R':
case 'r':
{
cout <<"Your choice: Rock";
break;
}
case 'P':
case 'p':
{
cout <<"Your choice: Paper";
break;
}
case 'S':
case 's':
{
cout << "Your choice: Scissors";
break;
}
case 'Q':
case 'q':
{
cout << "Bye Bye Bye";
break;
}
default:
cout<<"You enter nothing!"<<endl;
cout << "The valid choices are R/P/S/Q)";
}
return;
}
int RPScomp()
{
int comp=0;
const int MIN_VALUE =1;
const int MAX_VALUE =3;
unsigned seed = time(0);
srand(seed);
comp =(rand() % (MAX_VALUE - MIN_VALUE +1)) + MIN_VALUE;
return comp;
}
if (choice=='Q'||'q')
This is equivalent to
if ((choice == 'Q') || 'q')
Which is almost certainly not what you want. 'q' is a non-zero char literal, which is "truthy" and so this expression will never be false. It's akin to writing if (choice == 'Q' || true).
The solution is:
if (choice=='Q' || choice=='q')
The statement
if (choice=='Q'||'q')
always tests true and therefore sets your flag to terminate the loop.
Try:
if (choice=='Q'||choice=='q')
I think your if statement should be if (choice=='Q'|| choice=='q')
Your issue if with the if statement
if (choice=='Q'||'q')
{endit=1;}
the || 'q' part will always be true since 'q' in ASCII is not 0
Change your code to
if (choice=='Q'|| choice=='q')
{endit=1;}
In my program, I want users to choose between two choices. Simply, 1 or 2. I have written the program to where it will protect against an invalid numeric value such as 3 or 28, but I cannot protect against alphabetical input.
Code is as follows:
int whileInt = 0;
int choiceOne_One = 0;
while(whileInt == 0)
{
cin >> choiceOne_One;
if(choiceOne_One != 1 && choiceOne_One != 2)
{
cout << "Woah! That wasn't an option! Try Again.\n";
}
else if(choiceOne_One == 1)
{
whileInt++;
cout << "\nYou have died. Be more careful.\n";
}
else if(choiceOne_One == 2)
{
whileInt++;
cout << "\nYou have survived the alien invasion due to your cunning sense of "
"safety.\nCongratulations.\n";
}
}
My brain still works in Java, please help me figure this out. It will definitely be appreciated.
Try this :
#include <iostream>
using namespace std;
int main()
{
char input;
cin>>input;
switch(input)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
cout<<"valid input"<<endl;
break;
default :
cout<<"Invalid input"<<endl;
}
return 0;
}
You can define a case for all your valid inputs, leave the rest to default.
Integers from 0-9 have their ASCII values from 48-57 respectively.
This solution wont be helpful if you have
. input>9 or input<0
. input such as 1abc
Might be a bit late but my favorite way to do and this is what i use :
#include <iostream>
#include <string>
#include <limits>
//T is for our variable and lambdaFunc will be our lambda function or
//function pointer
template<typename T, typename lambdaFunc>
auto secureEntry(T& variable, LambdaFunc lFunc, std::string errorMessage) //can ommit error message
{
while(!(std::cin(variable)) && !lFunc(variable)){
std::cout << errorMessage << std::endl;
std::cin.clear();
std::ignore((std::numeric_limits<std::streamsize>::max)(), '\n');
}
}
int main(int argc, char* argv[]){
int mynumber = {0};
std::string errorMessage = "Please use a number bigger than 0 and lower than 5"
secureEntry(myNumber, [](int& mynumber) -> bool{
return mynumber > 0 && mynumber < 5;
}, errorMessage)
}
you can do this also
int whileInt=0;
int choiceOne_One = 0;
while(whileInt == 0)
{
cin >> choiceOne_One;
if (choiceOne_One == 1 || choiceOne_One == 2){
if (choiceOne_One == 1){
whileInt++;
cout << "\nYou have died. Be more careful.\n";
}
else {
whileInt++;
cout << "\nYou have survived the alien invasion due to your cunning sense of "
"safety.\nCongratulations.\n";
}
}
else {
cout << "Woah! That wasn't an option! Try Again.\n";
}
}
Try reading a std::string with std::getline, then simply compare the string with "1" or "2". Otherwise, you can just read the whole line with std::getline, then use std::stoi (C++11) to transform the read string into an integer. The result of std::stoi tells you whether the transformation was successful or not (i.e., whether the string represented an integer). If successful, then you can simply compare the integer with 1 or 2. If not successful, then an std::invalid_argument or std::out_of_range exception is thrown.
First case (with std::string comparison):
#include <iostream>
int main()
{
std::string input;
std::getline(std::cin, input);
if (input != "1" && input != "2")
std::cout << "Invalid input!";
}
Second case (using std::stoi):
#include <iostream>
int main()
{
std::string input;
std::getline(std::cin, input);
int n = std::stoi(input); // throws exception if cannot convert to int
if (n != 1 && n != 2)
std::cout << "Invalid input!";
}
If you change the program so that cin puts a User's answer to a std::string, then you could do tests on the string value.
If the string's length() was more than 1, it cannot be '1' or '2'
There are additional tests you can do, like std::isalpha(int ch)
#include <stdio.h>
#include <string>
#include <iostream>
int main(int argc, char * argv[]) {
std::string value;
std::cin >> value;
std::cout << "Value is " << value << "\n";
std::cout << "length of value is " << value.length() << "\n";
char ch;
ch = value.at(0);
if(std::isalpha(ch)) std::cout << "You did not enter a number" << "\n";
return 0;
}
robert#debian:/tmp$ g++ -Wall test.cpp
robert#debian:/tmp$ ./a.out
123
Value is 123
length of value is 3
robert#debian:/tmp$ ./a.out
abc
Value is abc
length of value is 3
You did not enter a number
I am facing problem in the below code. If the user enter more than one charater then my loop gets executed number of times equal to the length of the string entered by the user. My code is written in GNU c/c++ compiler.
Thanks in advance.
int continue_option()
{
char c;
loop:
fflush(stdin);
cin.ignore();
cout<<"\n\n\t\t\t\tPress (Y/y) - Continue / Press (N/n) - Exit :";
cin>>c;
if(c=='y'||c=='Y')
{
system("clear");
}
else if(c=='n'|| c=='N')
{
exit(0);
}
else
{
printf("\n\t\t\t\tInvalid Option.Try Again.....");
goto loop;
}
fflush(stdin);
}
First thing, don't use jumps. They are old style, and they make Dijkstra spin in his grave, on top of all the other bad consequences. I don't mean "vintage", I really mean old in the bad sense.
As of your question, I'd rather put the result in a std::string and only consider the first character in there:
std::string input;
std::cin >> input;
switch (input[0]) {
case 'y':
case 'Y':
//your code
break;
case 'n':
case 'N':
exit(0);
default:
std::cout << "Invalid text" << std::endl;
}
I would also refrain from using exit(), I'd rather rely on a function's return value to finally cause a return 0; in the main(), or some equivalent technique.
You can't stop the user from typing more than one character.
What you can do is ignore the rest of the line. You have already use cin.ignore() which ignores one character. You can use cin.ignore(large number) to ignore up to the large number or the end-of-line, whichever appears first.
Unlike flushing output files, fflush(stdin) doesn't really do anything.
Try using cin.get() or getch() to read just one character at a time. Also, I guess you'd be better off replacing the whole thing with a simple loop like:
char ch = '\0';
do
{
ch = getch();
}while((tolower(ch) != 'y') || (tolower(ch) != 'n'))
if(tolower(ch) == 'y')
{
//additional handling
}
else
{
exit(0);
}
Not exactly the same behavior, but should put you on track:
#include <iostream>
#include <iomanip>
bool is_valid_answer(char c)
{
switch(c)
{
case 'y':
case 'Y':
case 'n':
case 'N':
return true;
default:
return false;
}
}
bool continue_option()
{
std::cout << "Press (Y/y) to continue, (N/n) to exit: " << std::flush;
char c = '\0';
while (std::cin.get(c) && !is_valid_answer(c));
return ((c == 'y') || (c == 'Y'));
}
int main()
{
std::cout << "Continue option: " << continue_option() << std::endl;
}