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;

Recommended Answers

All 5 Replies

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.

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

getline and get have the same problem. Check out http://www.cplusplus.com/reference/iostream/istream/getline/ and http://www.cplusplus.com/reference/iostream/istream/get/ the prototypes are at the top of the page. fgets from <cstdio> does return the c-string that it reads in, but to get an integer out of it you'd need another function.

Out of curiosity, is there a reason you are opposed to having 1 extra line in the code?

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" ;

Alright, I'll just keep the extra line of code. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.