get function for files

hi,
I'm trying to read an integer value from file and I was wondering if I could use get function I wrote a simple code to understand how get function works but unfortunately I couldn't figure it out.so I need your help. Here is my simple code
1
2
3
4
5
6
7
fstream file;
	string filename;
	filename= "C:\\Users\\dell\\Documents\\Visual Studio 2010\\Projects\\first sağlama\\TextFile1.txt";
	file.open(filename,ios::in|ios::out);
	file.seekg(0,ios::beg);
	cout<<file.get();
	system("pause");

the output on the screen is 49. but what I wrote to textfile was 1234
Last edited on
49 is the ASCII code for character '1'.
Your code above reads just a single character.
Normally you'd do something like this:
1
2
3
    int num;
    file >> num;
    cout << num;

Last edited on
Or you could read each character and construct the integer a digit at a time:
1
2
3
4
5
6
7
8
9
10
11
12
13
        char c;
        int a = 0;
        while (file.get(c))
        {
            if (c >= '0' && c <= '9')
            {
                a *= 10;
                a += c - '0';
            }
            else
                break;
        }
        cout << a << endl;
But if I have more than 1 integer in the file how will the program understand where an integer starts and where it ends. I tried to put a certain cahracter like 'a' between each integer so when file.get() returns 97 program understands that a new integer starts but is there any other way? because the program should be able to retrieve the integer in the middle of the file
Last edited on
The example code I posted previously tests the character like this if (c >= '0' && c <= '9') at line 5.

As you can see, this loop will end when the character is not a digit. Commonly you would use a space or newline character to mark the end of the number. Though my code would also work with the letter 'a' because that is not a digit.
how was it the cahracter at line 5? I mean it is not indicated at the code you posted right ?
Sorry, I just meant that was the program line number where that code was to be found. I guess rather than helping, it was a distraction.
Oh ok I got it now:) thanks for the help bcoz although I used it in one of my earlier codes I just couldn't figure how to convert number of characters into integer I guess its bcoz I'm new and I have to practice a lot
anyways thanks again
Topic archived. No new replies allowed.