get() overloaded function ifstream

Oct 25, 2020 at 9:18pm
hey, I have been learning I/O, and am going over the get() function, I have learned that there are overloaded versions so wanted to try those version, but I can figure out how to get it to work. I have a text doc, with just a single number in it. and was wanting to take that in via the stream and print it out, but I am getting garbage values. I am wondering if maybe i am misunderstanding how this overloaded version works. I thought that it would get the input from the stream, from the text file, make the space available in the buffer specified by 'sizeof num' and then store than in the buffer, which i am then printing?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>
#include <fstream>	

int main()
{
	int num;
	std::ifstream in("test.txt", std::ios::in);

	if (!in)
	{
		std::cerr << "Cannot open file\n";
		return 1;
	}

	in.get((char*) &num, sizeof num);

	std::cout << num;

}
Oct 25, 2020 at 10:12pm
Look at the example of cppreference.com:
https://en.cppreference.com/w/cpp/io/basic_istream/get

get() deals with chars, not with ints, so if you try to write to an int storage place, you will indeed get garbage.

Maybe you want do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>

int main()
{
	char str[16];  // could hold a c-string

	std::ifstream in("test.txt");

	if (!in)
	{
		std::cerr << "Cannot open file\n";
		return 1;
	}

	in.get( str, 16 ); // Writes up to 15 chars (+ '\0') to str, or until '\n'.

	std::cout << str;

}


Be aware that numbers written within a text-file usualy will be ASCII-coded and hence consist also of characters.
'0' has ASCII-value 48, '1' has 49, and so on.
Last edited on Oct 25, 2020 at 10:45pm
Oct 25, 2020 at 10:43pm
I have a text doc, with just a single number in it. and was wanting to take that in via the stream and print it out, but I am getting garbage values.

If you are working with numbers you should probably just stick with the insertion operator>>.

The get() function works with either a single character or a C-string or or a streambuffer.

The overload "int get()" retrieves a single character or eof(). Realize that eof() is a value that cannot be held in an unsigned char (usually a negative value). This is the reason the function returns an int instead of a char, (whether a char is signed or unsigned is an implementation detail).

Oct 26, 2020 at 12:26pm
(extraction operator >>)
Topic archived. No new replies allowed.