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 filescodeblocksmingwbin..libgccmingw324.7.1includec++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.


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;

这可能对你有用,

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

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

return 0;
}
链接地址: http://www.djcxy.com/p/86966.html

上一篇: 在嵌入式Linux上使用C ++ Std Lib时出现异常段错误

下一篇: 为什么不能使用自动声明的变量?