Arpit
Arpit

Reputation: 12797

How to access this auto variable?

i declared a test variable of auto type but now i don't know how to access it. I know how to make this prograame work without auto but here i want to know how to access that auto variable.

int main() {
auto test = {'1','S'};
std::cout<<test; //error no match for operator... i tried using *test or *test[0] but no solution.  
cin.get();
return 0;
}

Compiler log :

Compiler: mingw
Executing  g++.exe...
g++.exe "C:\Users\Arpit\Desktop\delete.cpp" -o "C:\Users\Arpit\Desktop\delete.exe"   -std=c++11   
C:\Users\Arpit\Desktop\delete.cpp: In function 'int main()':
C:\Users\Arpit\Desktop\delete.cpp:5:12: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
In file included from c:\program files\codeblocks\mingw\bin\../lib/gcc/mingw32/4.7.1/include/c++/iostream:40:0,

                 from C:\Users\Arpit\Desktop\delete.cpp:1:
c:\program files\codeblocks\mingw\bin\../lib/gcc/mingw32/4.7.1/include/c++/ostream:600:5: error:   initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = std::initializer_list<char>]'

Execution terminated

How to print test?

Upvotes: 0

Views: 160

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409364

The variable test is of type std::initializer_list. You have to use iterators to get the values from it, or the new range-based for loop:

auto test = { '1', 's' };
for (const auto& i : test)
    std::cout << i << '\n';

Upvotes: 2

awesoon
awesoon

Reputation: 33691

You got this error since auto variable = { ... } declares an std::initializer_list, which do not have overloaded operator<< for std::ostream. You can use, for example, range-based for to get access to values from your list.

int main()
{
    auto test = {'1','S'};
    for(const auto& elem: test)
        std::cout << elem << ' ';
    std::cout << std::endl;

    return 0;
}

Upvotes: 2

Related Questions