0

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 by ultrasurf123: n/a

3
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by ultrasurf123
Featured Replies
  • 1

    [QUOTE]Is there any way to use something like get/getline without providing an argument for storage variable?[/QUOTE] If the type involved has default or trivial initialization, you could write such a function yourself. For example: [CODE]template< typename T > inline T get( std::istream& stm ) throw (std::runtime_error) { T temp ; … Read More

0

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 by mike_2000_17: Fixed formatting

0

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

1

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.