Extracting numbers from files

Okay, title says it all :P

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 [*] _ [*]
You could do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#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;
}

File contained:
text
25

Program output:
25
Uhm, neither of you really helped =P

And hamsterman, I post here because the tutorials don't make sense to me >_<...

You see, I have this:

1
2
3
4
5
short number;
    InputStream.open("example.txt");
    ifstream myfile ("example.txt" );
getline (myfile, number);
cout<<number.


File contained:
 
5


Program errors.
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.
Last edited on
Oh, now I get it. Thanks Fire, sorry Ham* :D

*Please speak the language I speak (it's called moron). I'm not fluent in Genius >_<
Topic archived. No new replies allowed.