How to use get() with arrays?

How do I use get() with arrays? I've looked at the article on the forums, but it isn't much help on what I want to do. I know I'm using get correctly, but the pointer isn't moving up in the array.

Meaning that when I read from the text file, the character that gets read is given to pointer and then to buffer. The next character read REPLACES the original character. What I want is that the next character gets placed in the next variable in the array.

I'm not sure where I went wrong, but it might be at the pointers?
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
#include <iostream>
#include <fstream>
#include <istream>
#include <string>


using namespace std;

void main (void){
	char buffer[61];
	char *pointer;
	pointer = buffer;	//points pointer to buffer
	ifstream Maps;
	Maps.open ("Map01.txt",ios::in);  //open file
	if(!Maps){	//check if file is open
		cout<< "error";
	}
	while (!(Maps.eof())){ //until end of file
		Maps.get(*pointer);	//Retrieve character value and give it to pointer, which then points it to buffer.
		}
	for (int i=0;i<60;i++){	//cout buffer.
		cout<<buffer[i];
	}
	system("pause");
}
There are several member functions get in class std::basic_istream. You use the function that reads only one character from the stream and places it in the first element of array buffer. So every next read overwrites already read character.

You should use another get function

basic_istream<charT,traits>& get(char_type* s, streamsize n)

for example

Maps.get( buffer, sizeof( buffer ) );

In this case the whole buffer will be filled if the stream has enough characters..
Last edited on
As for your code then it could look the following way


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
	const size_t N = 61;
	char buffer[N] = {};
	ifstream Maps( "Map01.txt" ) ;

	for ( size_t i = 0; i < N - 1 && Maps; i++ )
	{
		Maps.get( buffer[i] );
	}

	cout << buffer << endl;

	system("pause");
}


Last edited on
When I ran the code you gave, it worked like a charm!

Now I'm curios, how do you put the delimiting character?

Suppose I want the code to stop at '!', do I use

Maps.get(buffer, sizeof(buffer),'!');
Yes, there are two forms of function get that deals with character arrays.

basic_istream<charT,traits>& get(char_type* s, streamsize n,
char_type delim );

and

basic_istream<charT,traits>& get(char_type* s, streamsize n)

Effects: Calls get(s,n,widen(ā€™\nā€™))
I don't understand this part of your code. What does && maps do? I thought maps was the "variable" we gave to the stream? I understand the N-1 part, not the && Maps.

i < N - 1 && Maps
class std::basic_istream has (inherited) explicit conversion operator bool that returns true if the state of the stream is good and false otherwise..
Last edited on
Topic archived. No new replies allowed.