简体   繁体   中英

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();

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();

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

std::string result;
char ch;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM