This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
std::string to float or double
I am writing a calculator (learning C++), and just decided to make a calculator, since that was the first thing I did when learning Java.
The program does the following:
Asks the user for the first number
Asks what the user wants to do with the number (-,+,*,/)
Asks for the second number
Displays the result.
when grabbing a number from the user in Java I used Double.parseDouble(number) to check if what they entered is a number or not.
Is there a similar command in C++? Ive been doing research and it seems like you have to use tricks such as comparing it to ASCII equivalents etc.. basically a ton of code for a simple task... so before i take that route, I wanted to stop by here and see if perhaps there is some sort of call I can make to check if the input is a number. I need it to validate negatives, zero and positives, as well as numbers with decimals... everything else should be rejected and the user should be asked for input again.
When I did it in Java I used try/catch statement and if the input was invalid it would return the method (in other words, itself) so it would loop and ask the user for input again.
Thanks!
You can use strtod. It handles underflow and out of range values in a convenient way.
Additionally, as Joachim Pileborg notes, if you use C++11 compliant compiler, there is std::stod in the standard library.
Use the function double atof(const char*) ;
example usage:
const char* = "3.14159";
double pi = atof(myDouble);
How about using isdigit function.
Related
I realise this question probably has been asked before. I'm asking this as I don't know what to search for.
Hi, so I've started learning about arrays, but I'm not sure how (or if) they can help me with this problem:
Let's say I want the user to be able to choose what to do within my program. I then write a numbered list to the console:
Output "a"
Output "b"
Output "c"
The user will be asked to enter a number, and the number defines which function the program is going to run. What i want the program to do is instead of having me write this three times and changing out the numbers and letters:
if (numberInput == "1") {
functionA;
}
I just write something that takes the number from numberInput and then runs the function associated with it.
Again, I know this question probably has been asked a 1000 times before, so I'm wondering if someone has an idea on how I should go forward on searching for the answer. Thanks!
What you want is called a switch statement
I would start there
i think best here is switch/case stuff
exactly what you're askin about is to use array of function pointers.See
How can I use an array of function pointers?
you'll end up with
int c;
std::cin >> c;
....
(*fnpointers[c])();
This question already has answers here:
Using the scanf() function
(4 answers)
Closed 5 years ago.
char input[256];
do{
cout<<"..."; //prompt
scanf("%s",&input5); //user inputs string
if(strcmp(input5,"block")==0)
{} //if the user types block, then it finishes the loop and goes to the cout at the bottom
else if(strcmp(input5,"attack")==0)
{
cout<<"..."<<endl;
}
else if(strcmp(input5,"look")==0)
{
cout<<"..."
}
else
{
cout<<"..."<<endl;
}
}while(strcmp(input5,"block")!=0); //loop ends when block is typed
cout<<"...";
I am having issues with my do while loop. I am doing a project for school that involves a text adventure kind of game. The user is prompting how to respond to an attack. The desired command is "block", which will move the user on to the next sequence. When "block" is typed into the scanf, it endlessly loops and prints what is in the "else" condition. I don't see what the problem is and all feedback is appreciated.
I just tried your code and it works fine (though I removed the & in the scanf), and created 'input5' as a char array.
Though that aside, there's a few things that you might want to change. I'd stick to using 'cin' instead of scanf, as you're mixing C and C++. That would allow you to use a 'string' for 'input5', and compare them using the '==' operator, which is quite a bit cleaner. Maybe think of a more descriptive name than 'input5' too, as if you've got lots of 'inputX' variables then things will get messy.
Edit: I'd also refrain from "using namespace std;", as you might end up with naming collisions.
Most likely you don't need the & operator before input5 on the scanf line, because the things scanf expects for %s fields are already pointers/arrays. Although I don't see how input5 is declared, so I'm not sure if this is the (only) problem. You should have included that in the code snippet also.
EDIT: Just a note: It's not particularly elegant to mix C-style (scanf) and C++ style (cout) IO. You wouldn't have this problem with cin.
Obviously, the loop does not terminate because the string comparison does not return equality. And this must be because input5 does not contain the typed input (and for the same reason, the else clause is executed whatever the input).
As input5 is only modified by the scanf call, this must be the root of the evil. A simple debugging session would have revealed it immediately.
The reason is simple: you must pass scanf the address of the buffer, but you are actually passing the address of the address, and overwriting the value of the variable input5 (for which we don't have the declaration but can infer char* or const char*).
In a 32 bits environment, this could cause a crash by overwriting the stack. Under 64 bits, you'll need more typing to obtain it.
This question already has answers here:
Is there a TryParse equivalent in C++ (gcc)?
(4 answers)
Closed 7 years ago.
Hi im looking at the string conversion methods in c++ strtol, strtoll, strtoul, atol etc.
It seems every single one of them will return a 0 (or 0.0) as a result for a string that was impossible to convert.
Assuming that 0 is a completely valid correct input for my program how do I avoid converting nonsense strings to zero and make for example them throw some exception instead? Are there ready made functions that perform that way or do I have to wrap these with some of my own code.
Also could anybody explain me what might the reasons be that these functions are designed like this (Why build in the trouble of separating nonsense string parse result from hones-to-god "0" string parse results)?
Failure is indicated by setting errno, which is the old-fashioned C way of doing things.
You might find stol and friends more useful - they indicate failure by throwing an exception.
http://en.cppreference.com/w/cpp/string/basic_string/stol
You can use the std::stoi() std::stof() function family to do this. The functions will throw an exception for invalid input.
You may find useful boost/lexical_cast.
This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 8 years ago.
I need some tips on an assignment that I am currently working on. I need to create a program for converting time specs (n1y n2n n3d n4h n5m n6s -- note the amount of whitespace can vary between the different inputs) to seconds. One of the functions that I need to create is a function to validate the time spec input (as a const char*). The function header looks as follows:
// is_legal_time_spec:
// Checks if ctime_spec is a valid time spec
// In:
// ctime_spec != NULL
// Out:
// return -- true if the ctime_spec is a valid time spec
// false if otherwise
bool is_legal_time_spec( const char *ctime_spec ) {
return false;
}
Ive had some ideas about how to use the strpbrk(3) function for this, but I was wondering if there is another easier function that I can use to check the format of the time spec input.
Thanks in advance for your help.
Use strtok to break string into words, and then validate each words separately by parsing it or using sscanf. Then do simple mathematics to convert into time specs into seconds
I'm working through a list of practice problems to beef up my C++ skills (I'm a beginner), this one is stumping me.
Make a program that takes input from the user of a calculation (e.g. "2+2") and outputs the
answer (e.g. 4). It shouldn't matter if there are spaces or the formatting of the user's
input, so long as the basics (2 numbers and one connecting function) are fulfilled.
I think I have the basic idea down, I just don't understand two critical parts:
1) How take the input from the user as a string and put it into an array.
2) How to take members of an array and reconfigure them as a string.
Because you seem to have an idea what you want to do, I'll just answer the questions. Go ahead and try. :)
To read from the console in C++ you can include the iostream-library and use cin <<.
For example:
#include <iostream>
#include <string>
int main(void)
{
string yourVar;
// ...
cin >> yourVar;
//...
}
You should then be able to use the string like an array e.g. char c = yourVar[2];
Search about tokenizing and grammar. A very nice example which fits the description of your problem is thoroughly presented in the book : http://www.amazon.com/Programming-Principles-Practice-Using-C/dp/0321543726 among other things.
This will not only allow you to solve this problem but it will also allow you to create a much more powerful calculator, taking into account things such as operator precedence, parentheses, curly brackets etc.