I have a dynamically allocated memory:
//dynamic buffer
char *mybuffer;
cin>>n;
mybuffer=new char[n];
//open file for reading
ifstream inpt(filename.c_str(), ios::binary);
for(unsigned int i=0;i<n;i++){
//copy every single character into buffer
inpt.read(mybuffer[i],1);
}
says error, argument of type char is incompatible with type char*
I need to read the files character by character and store in buffer. Note that this is sample code. I actually should read multiple files and store in single buffer so I should use buffer with index.
How can I improve this code?
You should pass a pointer to char as input of ifstream::read , but you're passing a char.
inpt.read(&mybuffer[i],1);
^
The error
error, argument of type char is incompatible with type char*
is due to istream::read
takes pointer to char:
istream& read (char* s, streamsize n);
so you should write:
inpt.read( &mybuffer[i], 1);
I would suggest you to avoid allocating memory and pass to read.Here is the sample code which opens a file and reads each line into the "std::string" object and prints on the console. "std::string" would take care of all memory management and you can read it and use in your program.
int main()
{
std::string file = "input.txt";
std::string line;
std::ifstream text_filestream(file.c_str());
while(std::getline(text_filestream, line)) {
// now you can use the line object by anyway as per your requirement.
std::cout<<line<<std::endl;
}
}
I guess this improvement should be done in your program.
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.