How to read non ascii characters from a text file

时光毁灭记忆、已成空白 提交于 2019-12-12 01:27:48

问题


I found the length using seekg and tellg, then read them into an unsigned char*. The debugger is showing incorrect text though.

ifstream is (infile, ifstream::binary);
//find length
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);

char * buffer = new char [length];
is.read (buffer,length);
//delete[] buffer;  removed

//size_t cipherTextLength = length;                                removed    

//unsigned char* cipherText = new unsigned char[cipherTextLength]; removed

//is.read (reinterpret_cast<char*>(cipherText),length);            removed

edit:

text file is something like this:

.l F4"w2ÍögPl Ð    l œ›”  ÿÿÿPl (goes on)

debugger shows something like:

ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍýýýý««««««««þîþîþîþ

edit: now textfile only shows . l and debugger shows .\xl


回答1:


I think you are not adding \0 to the buffer. I did faced the same issue and solved it by adding +1 to the length.

char *buffer = new char [length + 1];
buffer[length] = 0; // Adding terminating character in content.
iFileStream.read(buffer, length);
std::string str(buffer);

Now the str should be correct. Hope this helps.




回答2:


As your code if.read can get file binary. your program is string output except. you can print character on by on use %c from buffer



来源:https://stackoverflow.com/questions/29813644/how-to-read-non-ascii-characters-from-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!