I have a file with a text on the top line, and a number on the second. How do I extract the number into a variable... Like, int number; or something along these lines. Please help [*] _ [*]
#include <iostream>
#include <fstream>
#include <sstream> //sstream auto-includes string.h, so no need to include that too
#include <conio.h> //conio.h for "_kbhit()"
int _tmain()
{
std::string input;
int intFromFile = 0;
std::ifstream file;
file.open( "test.txt", std::ios::binary );
if( file.is_open() )
{
std::cout << "File open.\n";
std::getline( file, input, '\n' ); //get the text line
std::getline( file, input ); //get the integer
std::stringstream ss( input ); //create a stringstream with the input variable
if( ss >> intFromFile ) //if the 'input' goes into the int...
std::cout << "Integer from file was " << intFromFile << '\n';
file.close();
}
else
std::cout << "Error opening file.\n";
std::cout << "Please press a key to exit.\n";
while( ! _kbhit() ) //while there's no key press
{
//do nothing until a key is hit
}
return 0;
}
InputStream doesn't seem to exist, remove that line.
getline wants an std::string as its second argument, you can't get directly to a number like that. You will either have to parse the number yourself or use myfile >> number; like hamsterman suggested.