Skeve
Skeve

Reputation: 253

Why is it not possible to cin to an auto declared variable?

I am experimenting with C++11 features using the GCC compiler. I have discovered that the following code does not compile and I'm not sure why. I was expecting that the type of name would be automatically deduced from the initialisation value.

int main()
{
    auto name = "";
    cin >> name; // compile error occurs here
    cout << "Hello " << name << endl;
    return 0;
}

The error produced is:

cannot bind 'std::istream {aka std::basic_istream}' lvalue to 'std::basic_istream&&'| c:\program files\codeblocks\mingw\bin..\lib\gcc\mingw32\4.7.1\include\c++\istream|866|error: initializing argument 1 of 'std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&&, _Tp&) [with _CharT = char; _Traits = std::char_traits; _Tp = const char*]'|

What exactly does this mean?

Note, if you explicitly specify name as a string there is no problem.

Upvotes: 3

Views: 2029

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129374

The reason you can't "write" to your auto variable is that it's a const char * or const char [1], because that is the type of any string constant.

The point of auto is to resolve to the simplest possible type which "works" for the type of the assignment. The compiler does not "look forward to see what you are doing with the variable", so it doesn't understand that later on you will want to write into this variable, and use it to store a string, so std::string would make more sense.

You code could be made to work in many different ways, here's one that makes some sense:

std::string default_name = "";
auto name = default_name;

cin >> name;

Upvotes: 4

Hitesh Vaghani
Hitesh Vaghani

Reputation: 1362

This might be useful to you,

string getname()
{
  string str;
  cin>>str;
  return str;
}

int main()
{
    auto name = getname();
    cout << "Hello " << name << endl;

return 0;
}

Upvotes: 0

Related Questions