I'm working on an assignment. I need to have the user input a fraction in #/# format . How can I set the top and bottom to two separate variables?
Here's a chunk of code I've tried, but I keep getting nothing for the second variable:
#include <iostream>
#include <conio.h>
#include <cstdio>
#include <regex>
using namespace std;
int main() {
string firstFraction;
cout << "Enter your first real Fraction: " << endl;
firstFraction = cin.get();
string delimiter = "/";
string numerator = firstFraction.substr(0,firstFraction.find(delimiter));
size_t pos = firstFraction.find("/");
string denominator = firstFraction.substr(pos);
cout << numerator << " / " << denominator << endl;
_getch();
return 0;
}
Try something like this:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string fraction;
cout << "Enter your first real Fraction: " << endl;
getline(cin, fraction);
istringstream iss(fraction);
string numerator, denominator;
getline(iss, numerator, '/');
getline(iss, denominator);
cout << numerator << " / " << denominator << endl;
cin.get();
return 0;
}
firstFraction = cin.get();
Print firstFraction after this line and see whether it contains what you thought it contains. Looking in the reference (something you should be doing!) ...
[..] Reads one character and returns it if available. [..]
... we learn that you're only reading a single character (of unformatted input). How do you intend to split the resulting (single character) string?
There are multiple ways of doing it correctly, which one to choose depends a lot on your needs. A short, non-complete list:
std::getline the whole line, and then searching for / within it
std::getline until the next /, std::getline until end of line. (I don't really recommend this)
Formatted input, for example :
#include <iostream>
using namespace std;
int main() {
unsigned int nominator, denominator;
char sep;
cin >> nominator >> sep >> denominator;
if (!cin || sep != '/') {
cerr << "Well... you know, that failed somehow." << endl;
return 1;
}
cout << "Fraction: " << nominator << "/" << denominator << endl;
return 0;
}
Though this also allows input like
3 / 4
and
3
/
4
And of course, you should abstract this, e.g. make a fraction class, and write a (member) function read_fraction (and also provide a suitable operator>> if you want).
This could be as simple as
#include <iostream>
#include <sstream>
#include <string>
//using namespace std; dangerous! Use with caution
int main()
{
int num; // want a number as numerator
int denom; // and a number as denomenator
char divsign; // and a character to hold the /
std::cout << "Enter your first real Fraction: " << std::endl;
// user input contains at least a numerator a / and a denominator
// anything less fails. anything more will slip through. If this is a
// problem, add another >> to see if there is more in the stream
if (std::cin >> num >> divsign >> denom && // all input read successfully
divsign == '/') // and the division operator was present
{ // got what we need. Print it.
std::cout << num << " / " << denom << std::endl;
}
else
{ // bad input. insult user.
std::cout << "Bogus user input. No fraction for you" << std::endl;
}
return 0;
}
It has a number of potential failure cases, such as:
999999999999 / 2
Bogus user input. No fraction for you
Integer overflow. The input was too big. And
1/1dfjklghaljkgadlfhjgklahd
1 / 1
Crap after the last character
Related
So I'm trying to make a program that asks a user for a planet, this is stored as a string. I want to use a switch statement to make decisions (like if it's earth do this, if it's mars do this). I am aware that switch statements only take ints, so I took the string and translated it to its hex value. The issue I'm stuck on is how do I have the hex value saved as an int.
I am aware that it would be way easier to do a bunch of nested if statements, but I find that really ugly and bulky.
Here is what I have so far:
/*
* Have user input their weight and a planet
* then output how heavy they would be on that planet
* if planet is wrong
* output it
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string returnanswer(string x) {
string dat = x;
int test;
ostringstream os;
for (int i = 0; i < dat.length(); i++)
os << hex << uppercase << (int) dat[i];
string hexdat = os.str();
cout << "Text: " << dat << endl;;
cout << "Hex: " << hexdat << endl;
return hexdat;
}
int main() {
int weight;
string planet;
cout << "Please enter your weight: " << endl;
cin >> weight;
cout << "Please enter Planet" << endl;
cin >> planet;
returnanswer(planet);
return 0;
}
One way to convert a string hex to an int (using the suggestion from C++ convert hex string to signed integer) would be this:
unsigned int num;
stringstream ss;
ss << hex << hexdat;
ss >> num;
num would now contain the int value of hexdat.
On a side note, instead of converting the planet name to a hex and then to a string, you should consider using an unordered_map (as others have suggested), for example unordered_map<string, Enum> that maps user input planet names to Enum values. The planet Enum would look something like this:
enum Planet {mercury, venus, earth, mars, jupiter, saturn, uranus, neptune};
I was typing this and it asks the user to input two integers which will then become variables. From there it will carry out simple operations.
How do I get the computer to check if what is entered is an integer or not? And if not, ask the user to type an integer in. For example: if someone inputs "a" instead of 2, then it will tell them to reenter a number.
Thanks
#include <iostream>
using namespace std;
int main ()
{
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}
You can check like this:
int x;
cin >> x;
if (cin.fail()) {
//Not an int.
}
Furthermore, you can continue to get input until you get an int via:
#include <iostream>
int main() {
int x;
std::cin >> x;
while(std::cin.fail()) {
std::cout << "Error" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> x;
}
std::cout << x << std::endl;
return 0;
}
EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).
#include <iostream>
#include <string>
int main() {
std::string theInput;
int inputAsInt;
std::getline(std::cin, theInput);
while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
std::cout << "Error" << std::endl;
if( theInput.find_first_not_of("0123456789") == std::string::npos) {
std::cin.clear();
std::cin.ignore(256,'\n');
}
std::getline(std::cin, theInput);
}
std::string::size_type st;
inputAsInt = std::stoi(theInput,&st);
std::cout << inputAsInt << std::endl;
return 0;
}
Heh, this is an old question that could use a better answer.
User input should be obtained as a string and then attempt-converted to the data type you desire. Conveniently, this also allows you to answer questions like “what type of data is my input?”
Here is a function I use a lot. Other options exist, such as in Boost, but the basic premise is the same: attempt to perform the string→type conversion and observe the success or failure:
template <typename T>
auto string_to( const std::string & s )
{
T value;
std::istringstream ss( s );
return ((ss >> value) and (ss >> std::ws).eof()) // attempt the conversion
? value // success
: std::optional<T> { }; // failure
}
Using the optional type is just one way. You could also throw an exception or return a default value on failure. Whatever works for your situation.
Here is an example of using it:
int n;
std::cout << "n? ";
{
std::string s;
getline( std::cin, s );
auto x = string_to <int> ( s );
if (!x) return complain();
n = *x;
}
std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";
limitations and type identification
In order for this to work, of course, there must exist a method to unambiguously extract your data type from a stream. This is the natural order of things in C++ — that is, business as usual. So no surprises here.
The next caveat is that some types subsume others. For example, if you are trying to distinguish between int and double, check for int first, since anything that converts to an int is also a double.
There is a function in c called isdigit(). That will suit you just fine. Example:
int var1 = 'h';
int var2 = '2';
if( isdigit(var1) )
{
printf("var1 = |%c| is a digit\n", var1 );
}
else
{
printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
printf("var2 = |%c| is a digit\n", var2 );
}
else
{
printf("var2 = |%c| is not a digit\n", var2 );
}
From here
If istream fails to insert, it will set the fail bit.
int i = 0;
std::cin >> i; // type a and press enter
if (std::cin.fail())
{
std::cout << "I failed, try again ..." << std::endl
std::cin.clear(); // reset the failed state
}
You can set this up in a do-while loop to get the correct type (int in this case) propertly inserted.
For more information: http://augustcouncil.com/~tgibson/tutorial/iotips.html#directly
You can use the variables name itself to check if a value is an integer.
for example:
#include <iostream>
using namespace std;
int main (){
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
if(firstvariable && secondvariable){
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}else{
cout << "\n[ERROR\tINVALID INPUT]\n";
return 1;
}
return 0;
}
I prefer to use <limits> to check for an int until it is passed.
#include <iostream>
#include <limits> //std::numeric_limits
using std::cout, std::endl, std::cin;
int main() {
int num;
while(!(cin >> num)){ //check the Input format for integer the right way
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid input. Reenter the number: ";
};
cout << "output= " << num << endl;
return 0;
}
Under C++11 and later, I have the found the std::stoi function very useful for this task. stoi throws an invalid_argument exception if conversion cannot be performed. This can be caught and handled as shown in the demo function 'getIntegerValue' below.
The stoi function has a second parameter 'idx' that indicates the position of the first character in the string after the number. We can use the value in idx to check against the string length and ascertain if there are any characters in the input other than the number. This helps eliminate input like 10abc or a decimal value.
The only case where this approach fails is when there is trailing white space after the number in the input, that is, the user enters a lot of spaces after inputting the number. To handle such a case, you could rtrim the input string as described in this post.
#include <iostream>
#include <string>
bool getIntegerValue(int &value);
int main(){
int value{};
bool valid{};
while(!valid){
std::cout << "Enter integer value: ";
valid = getIntegerValue(value);
if (!valid)
std::cout << "Invalid integer value! Please try again.\n" << std::endl;
}
std::cout << "You entered: " << value << std::endl;
return 0;
}
// Returns true if integer is read from standard input
bool getIntegerValue(int &value){
bool isInputValid{};
int valueFromString{};
size_t index{};
std::string userInput;
std::getline(std::cin, userInput);
try {
//stoi throws an invalid_argument exception if userInput cannot be
//converted to an integer.
valueFromString = std::stoi(userInput, &index);
//index being different than length of string implies additional
//characters in input that could not be converted to an integer.
//This is to handle inputs like 10str or decimal values like 10.12
if(index == userInput.length()) isInputValid = true;
}
catch (const std::invalid_argument &arg) {
; //you could show an invalid argument message here.
}
if (isInputValid) value = valueFromString;
return isInputValid;
}
You could use :
int a = 12;
if (a>0 || a<0){
cout << "Your text"<<endl;
}
I'm pretty sure it works.
Sorry for the simple question, but I couldn't find an already available answer elsewhere.
I am building a fractional calculator that can either add, subtract, divide, or multiply two fractions(e.g 4/3 + 5/2). Firstly however, I need to parse out different elements of the user's input, like the arithmetic operator, and the numerator and denominators of the two fractions and store those elements in order to manipulate them down the line.
I thought of using a series of getline(string) while altering the default delimiter to discard whitespace and / signs. However, when I try to execute my program, there seems to be issues with getline(string).
Might somebody be able to point out my surely amateur mistake? The compiler isn't throwing any errors, so I'm a bit lost on what it might be.
EDIT: I'VE SINCE BEEN ABLE TO RESOLVE THE ISSUE THANKS TO HELP. THANK YOU EVERYONE
#include <string>
#include <iostream>
using namespace std;
int main()
{
string numeratorfirst;
string denominatorfirst;
string arithoperator;
string numeratorsecond;
string denominatorsecond;
cout << "Enter the two fractions and the operator you want to use(IE: 3/4 + 4/6): ";
getline(cin, numeratorfirst, '/');
getline(cin, denominatorfirst, ' ');
getline(cin, arithoperator);
getline(cin, numeratorsecond, '/');
getline(cin, denominatorsecond, ' ');
cout << " " << endl;
cout << "Your fraction is: " << numeratorfirst << "/" << denominatorfirst << " " << arithoperator << " " << numeratorsecond << "/" << denominatorsecond << endl;
system("pause");
return 0;
}
It might be easier using scanf():
int numeratorfirst;
int denominatorfirst;
char arithoperator;
int numeratorsecond;
int denominatorsecond;
cout << "Enter the two fractions and the operator you want to use(IE: 3/4 + 4/6): ";
int tokens = scanf("%d/%d %c %d/%d", &numeratorfirst, &denominatorfirst,
&arithoperator, &numeratorsecond, &denominatorsecond);
if (tokens != 5)
return 1;
This works, and it rejects invalid inputs like "foo/bar + baz/qux".
If you want a "more C++ like" solution, try this:
int numeratorfirst, denominatorfirst, numeratorsecond, denominatorsecond;
char slashfirst, slashsecond;
char arithoperator;
cout << "Enter the two fractions and the operator you want to use(IE: 3/4 + 4/6): ";
cin >> numeratorfirst >> slashfirst >> denominatorfirst >> arithoperator
>> numeratorsecond >> slashsecond >> denominatorsecond;
if (!cin || slashfirst != '/' || slashsecond != '/')
return 1;
When I run this program and input, for example, the number 7, the final cout command only works occasionally. Otherwise, the program exits successfully but the result is not printed. Why is this happening?
#include <iostream>
#include <cmath>
double treble(double);
int main()
{
using namespace std;
cout << "Enter a number:" << endl;
double numways;
cin >> numways;
numways = treble(numways);
cout << "Your number trebled is: " << numways << endl;
return 0;
}
double treble(double n)
{
return n * 3;
}
You should put using namespace std; outside of all function declarations, right under your #include directives. Also, when you say it's not printing, is it that the console is closing before displaying your result? In that case, I would advocate using a simple cin to "pause" the program. You can do it exactly as #Nihar says, though I might suggest using a string instead of an int so that it doesn't break if you accidentally type something other than an int.
Something like this:
#include <iostream>
#include <cmath>
using namespace std;
double treble(double);
int main(){
cout << "Enter a number:" << endl;
double numways;
cin >> numways;
numways = treble(numways);
cout << "Your number trebled is: " << numways << endl;
string foo;
cin >> foo;
return 0;
}
double treble(double n){
return n * 3;
}
try with this => put
int temp;
cin>>temp;
before return 0; to pause the program, because the execution finished (successfully) before the last output could be written to the console.
I'm trying to write a c++ program that tests each input integer, and stops if the input is invalid.
Here is my code, without the testing part:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
do
{
cout << "\nPlease enter an integer: ";
cin >> i;
cout << endl << i << endl;
} while(i != 0);
system("Pause");
return 0;
}
How can I test the input for validity?
The easiest is to use std::getline to read a whole line of input into a std::string, and then test whether that string is a valid integer specification.
It's also possible to do this by testing the failure state of cin, and clearing it, but that way lies an assortment of complications that you don't want.
In order to test the string you can use a high level std::istringstream (just read from it and test its failure state after) or, more efficient but a little more complicated, strtol from the C library (the latter is what a C++ stream uses internally).
You need to test whether a string is an integer without crashing.
You can do this with strtol(). It converts the string to an integer, and reports on the first character that is not a legal char for a number. No invalid characters means the entire string was an integer.
There is a good description and example of how to use it here:
http://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
do
{
cout << "\nPlease enter an integer: ";
while(!(cin >> i))
{
cin.clear();
cin.ignore();
cout << "\nInput was invalid, please re-enter: ";
}
cout << endl << "The integer is: " << i << endl;
} while(i != 0);
system("Pause");
return 0;
}