In C++, I know that if I need to read something from a file, I can do this:

int x;
ifstream ifs("data.txt");
ifs >> x;

However, is there a function that simply returns the value of whatever I'm feeding in? For example, if I had this:

bool arr[100];
int x;
ifstream ifs("data.txt");
ifs >> x;
arr[x] = true;

Would I be able to do away with the ifs >> x part? Is it possible to have something like

arr[function_of_something(ifs,...)] = true;

Edited 5 Years Ago by ultrasurf123: n/a

I think the short answer is, in that case, no. The ifs call returns a pointer to an ifstream object, not the value read in from the file -- this allows you to chain calls like ifs >> x >> y >> z;, where y and z are two other declared variables.

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Is there any way to use something like get/getline without providing an argument for storage variable?

Is there any way to use something like get/getline without providing an argument for storage variable?

If the type involved has default or trivial initialization, you could write such a function yourself. For example:

template< typename T > inline
T get( std::istream& stm ) throw (std::runtime_error)
{
    T temp ;
    if( !( stm >> temp ) ) throw std::runtime_error( "bad stream input" ) ;
    return temp ;
}

And then:

try { std::cout << get<int>( std::cin ) << '\n' ; }
    catch( const std::runtime_error& ) { std::cerr << "error in input\n" ; }

But it doesn't buy you much over:

int i ; if( std::cin >> i ) std::cout << i << '\n' ;
    else std::cerr << "error in input\n" ;
This article has been dead for over six months. Start a new discussion instead.