Trts
Trts

Reputation: 1069

Reading char by char from a file and concatenate the result into an array of chars

I have a text file and read from it character by character. But I would like to concatenate these characters and have an array of characters.

As far as I can understand, I should use strcat. But I fail to to convert a char read from a file into a const char* so that I could use strcat:

char * strcat ( char * destination, const char * source );

In the debugger I can see that chr has "Bad Ptr". Will you be so kind as to help me?

ifstream infile;
infile.open( "Gmv.txt", ifstream::in);

char result[1000]; 

while (infile.good())
{       
    character = infile.get();
    const char * chr = reinterpret_cast<const char *>(character);
    strcat(result, chr);
}   
infile.close();

Upvotes: 0

Views: 3301

Answers (2)

user93353
user93353

Reputation: 14039

Assuming your files is 999 chars or less, this should work (no error checks added). There is no need to use strcat. As a matter of fact, it's stupid to use strcat here.

ifstream infile;
infile.open( "Gmv.txt", ifstream::in);

char result[1000]; 
int i = 0;
while (infile.good())
{       
    result[i] = infile.get();
    ++i;
}

result[i] = 0; // Add the '\0' at the end of the char array read.

infile.close();

strcat takes a char array terminated by 0 ('\0') as the 2nd param. your char isn't terminated by 0. Hence you get the bad pointer error.

BTW, you can shorter the while to this

while (infile)
    result[i++] = infile.get();

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409176

Why use an array as a string, when C++ have std::string:

std::string result;
char ch;

while (infile >> ch)
    result += ch;

Upvotes: 1

Related Questions