Best way to let user decide which function to run in C++? - c++

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])();

Related

How to write output of two different functions at the same times on separate lines in console? (C++, Windows 10)

I have the write() function which takes a string and an int for time as parameters. It takes the given string and writes the same string, letter by letter, with a set time delay.
For example, write("Cat is moving", 50) would output each letter one after the other with a 50 millisecond delay.
Right now I am wondering how I could make it so the console can output 2 different write() functions on the screen at the same time, on two separate lines of the console, without overlapping each other.
I tried doing something with multi-threading but it didn't work and I believe there has to be a simpler way.
This program is intended for Windows only.
I did implement a change cursor position function already, so that shouldn't be a problem.
This is the function:
void write(string word, int time)
{
for (int i = 0; i < word.length(); i++)
{
cout << word.at(i);
Sleep(time);
}
}
You are basically asking for a way for your program to be logically running several instances of the same function at the same time (without using recursion).
Although this can be accomplished by using multithreading, I don't recommend doing this, because in your case, this will probably introduce more problems than it will solve.
An alternative to multithreading may be to use coroutines, which were introduced in C++20. If you make write a coroutine instead of a function, then you may be able to solve the problem by having several of these coroutines logically running at the same time (they will probably not actually be running at the same time, because they will be suspended most of the time).
Unfortunately, I have no practical experience with coroutines, so I am unable to provide the details of a solution which would use coroutines. All I can say is that they are probably worth looking into for you, because as far as I can tell, they coincide with your way of thinking and with your way of wanting to solve the problem.
A more traditional way of solving the problem in C++ would be the following:
In the main loop of your program, you could call a function write_next_characters (which you write yourself) every 50 milliseconds, which writes the next characters of all words that are currently to be written.
In order for this function to work, your program will have to keep track of
a list of all words that are currently to be written,
the screen coordinates to which each word is to be written, and
how many characters of each word have already been written.
The function write_next_characters should receive a pointer to this information whenever it is called by the function main. It can then jump to the appropriate screen coordinates and print the next letter of each word. It will also have to update the state information mentioned above.
I would suggest that you define the following struct which contains the state information mentioned above for every word:
struct word_state
{
//the word that is to be written
std::string word;
//the screen coordinates to which the word is to be written
int x;
int y;
//how many characters have already been written
int written;
};
For every word that you are currently writing, you will have to create one object of type word_state. You can use a container of type std::list<word_state> to keep them in a linked list. I believe that using a linked list is appropriate, so that you can easily remove words from the list after the last character of that word has finished printing.

C++ Variables from external file using ifstream

I've written a program in VB which exports data into a text file, which I want to be read by another program in C++ and then that data be assigned as a variable. The program is essentially a quiz and the program I wrote in VB is question maker that exports all the data required into the text file.
Below is the text file:
test question|test A|test B|test C|test D|A|100|0|0|0|Right, I know this. The answer is 100% A. Good luck!|B|100|0|
From left to right we have, the question, AnswerA, AnswerB, AnswerC, AnswerD, the correct answer, percent 1, 2, 3, 4, (for polling an audience of what they think the answer may be) a friend's answer, a wrong answer (the program eliminates two wrong answers at one point, this answer is the remaining wrong answer) and percent 1 and 2 again (in case they eliminate 2 wrong answers but still want a poll).
I did quite a lot of google searching but found nothing to my following question (perhaps due to the fact I used the wrong keywords, I'm not too educated when it comes to programming jargon). What I want the C++ program to do is read the file and when it sees "|" it knows that what is coming is a new variable. Would I be better using ifstream or something else and how would I tell the program to identify the "|" and make it read whatever is in between as a variable?
Look at the documentation for istream::getline. You can use the | character as a delimiter.

C++ Running Code from file

This might seem a bit far fetched and possible off-topic (sorry if it is), but I'd like to know for sure if it is possible or not.
I am working on a Q and A program.
The text file is laid out in a Question tab Answer newline style.
My question is this: Is it possible to read an answer as a function.
Example:
Question - What time is it? / Answer - getCurrentTime()
Question - What is today's date? / Answer - getCurrentDate()
Then the program, though string parsing, knows that this is a function without an argument and calls the function getCurrentTime() or getCurrentDate() which prints the time or date respectively.
This is possible using an array of function pointers. You just load all the functions into the array. How you obtain the correct index is up to you. The only useful way I can come up with is maintain a second array containing the function names in the same positions as the functions in the function array. Then search the function name array and use the index in that array to access the correct function in the function array. If you need a better explanation leave a message. It is very late at night here and I need to work in the morning.
Barmar's solution will work to and is the better way to go about it but use function pointers.
Hope this helps
dannyhut

A good, simple, portable solution for waiting until enter is pressed in C++

Why not this?
cin.ignore (getchar(),'\n');
I'm not a professional programmer, and barely I can consider myself an amateur, but this is my little effort.
After looking thoroughly between all the solutions on the web that could be simple, portable and easy to understand (especially for a newbie like me), I haven't seen nothing really acceptable (especially for a newbie like me).
After many, many unsuccessful tries I wrote this line. And it worked!
And to me it sounds like a pretty elegant solution.
I mean: it's just one line of code, it's easy to remember, it doesn't need any further declared variable, you don't have to get in too much abstraction to understand it.
And it works, in every scenario I tried it.
If it's not a good solution, is there anybody good-willing enough to explain it?
[EDIT]
Thanks you all for all the proprer answers. But either me or you are missing the point.
What I'm questioning about is not if the solution I posted was working or not, because it works!
At least on my computer, and in all the executables I'm working on (I don't want to seem stubborn, try for yourselves for taking away credit from me. An example as I use it is at the end).
And none of the side effects you are talking about are showing up.
The line answers to my first enter, and it answers only to an enter - not "any" char.
My concerns are about the fact that I haven't seen it wrote anywhere, and considering myself the poorest of the programmer that surprised me to have found a solution from scratch.
short WaitForEnter ()
{
cout << "Press ENTER to continue\n";
cin.ignore (getchar(),'\n');
return 0;
}
Let's look at definition of ignore:
istream& ignore (streamsize n = 1, int delim = EOF);
Extract and discard characters
Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.
The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag.
So your line of code will wait for you to enter one character in to console (any character) not enter (\n);

Double.parseDouble() equivalent in C++? [duplicate]

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.