I'm trying to have the user enter a word or two (specifically a name), and then be able to recall that name later in the program as a variable (or some other type of memory storage that I've yet to hear of). How do I store it?
Thanks
Printable View
I'm trying to have the user enter a word or two (specifically a name), and then be able to recall that name later in the program as a variable (or some other type of memory storage that I've yet to hear of). How do I store it?
Thanks
In a std::string? You should use fgets, I guess. (Elysia does the fgets proselytizing, so you should find one of her posts.)
This is the C++ programming forum though, so we tend to do C++ I/O stream proselytising instead.
PAragonxd, what have you learnt about reading in user input?
Well, you may remember that I'm very new around here, and to C++ in general... so assume that I know minimum.
EDIT: But please, mind your time. I really don't need a huge lengthy explanation, so I don't want you to spend your time writing one.
If the variables which you want to name at run-time are of the same type, I would picture this as a job for an std::map<> container.
Edit: This code is quite over simplistic yet it clearly shows the concept I wanted to show you.Code:std::map<std::string, int> myVariables;
void AddVariable(std::string name, int data)
{
myVariables[name] = data;
}
void GetVariableName()
{
std::string name;
std::cin >> name;
myVariables[name] = 0;
}
void SetVariableData(const std::string& name)
{
int data;
std::cin >> data;
myVariables[name] = data;
}
// ...
I didn't imagine a simple process would require all that, maybe I didn't ask my question clear enough.
I'm aiming to store a name in the same way you would store a numeral variable. Is it even possible?
Thanks for the help though desolation, even if I didn't quite understand it.
That does a nice job of making me feel like a moron :P.
Oh you mean Elysia is a 'her'?
I'd go for the first-hand knowledge if I were you, and go straight to the FAQ. (hey that ryhmes!:) )
http://faq.cprogramming.com/cgi-bin/...&id=1043284351
Code:#include <iostream>
int main()
{
std::string name1;
std::string name2;
std::cout << "Enter a name:\n";
std::cin >> name1 >> name2;
std::cout << "You printed: " << name1 << ' ' << name2 << '\n';
return 0;
}
Awesome, thanks robwhit :D
Oh... Sorry I thought you wanted to actually name a variable and not have a variable contain a string.
Yeah I'm sorry about that, I didn't think before I asked :P.
Thanks a lot for your attempt though.
Just saw your edit. I clearly didn't intend to make you feel like a moron and I'm sorry if I looked like so.
Lol, don't worry about it :P. I figured it wasn't on purpose.