Is there any way that you can store data input from a user of unknown type into
an auto variable? It looks like I must immediately initialize the variable and there does not seem a way to do that without limiting the type of user input.
std::cin >> strength;
this gives an error message:
error: declaration of 'auto strength' has no initializer|
I had a book that was talking about c++0x(c++11) and the auto keyword and the explanation seemed to imply you could input what ever into an auto variable and yet you must immediately initialize the variable. I was wondering if I was missing something and could not find any answer. Thanks for answering.
Basically it deduces the type from a given value. Ex if you set an auto value equal to a double auto becomes double if you set auto even to a string it becomes a string value same with iterators and lambdas and templated stuff like that.
Basically the format is this
auto variable_name = value_of_a_certain_type;
//variable_name is now the type of the value
1 2 3 4
auto num = 1.2;
//num is now a double
auto str = "Hello";
//str is now a string
i never said one is neccesary to use with the other. as shown above by your being too lazy to type out the type, and dischs example, templates arent required. i only said that ive typically seen auto used in those cases i mentioned
Write a program with four overloaded square() functions that multiply a number by itself and take int, long, float, and double as their only parameter. Store the result of the function in an auto-typed variable and display it.
This made me wonder what the point of the above exercise was because I had already worked on overloaded functions and it seemed pretty annoying to do so much work just to store it in one auto variable.(What a challenge!) I started to lose confidence that there wasn't more to auto. I thought all you guys would surely be able to point out what I had missed. So far I do not believe I have missed anything and will probably toss the book aside.
This is the code I was reading in a book that said I must immediately initialize an auto variable:
auto uses the type of the initializer to determine the type of the variable to declare. If there is no initializer, there is no information available for it to use to determine the type the variable should be.