简体   繁体   中英

Issue when convert string to NSString

I want to covert C++ string to NSString to use in iOS app.

But sometimes the result is nil for C++ string with strange suffix format.

For example: a C++ string "but in fact it turned out to be you!$\\211/" will produce nil after convert to NSString .

mainFile.open(filePath, std::ios::binary);
mainFile.seekg(current_offset);
char buffer[size]; 
mainFile.read(buffer, sizeof buffer);
string tempString = string(buffer)
NSString *testString = [NSString stringWithCString:tempString.c_str() encoding:NSUTF8StringEncoding];

When cout << tempString I still read the string content with a strange code suffix, but it produces nil after convert to NSString

Anyone know how to fix this?

Why bother with the C++ portion at all?

NSString *filePath = @"/path/to/some/file.txt";
NSFileHandle *input = [NSFileHandle fileHandleForReadingAtPath:filePath];

[input seekToOffset:current_offset];

NSData *bytes = [input readDataOfLength:size];
if (bytes)
{
    NSString *str = [[NSString alloc] initWithData:bytes encoding:NSUTF8StringEncoding];
}
else
{
    NSLog(@"Unable to read from file");
}

If str is nil , then it means that the data is not encoded as UTF8, so you need to find what encoding your data is actually in. If it came from a Windows computer, try NSWindowsCP1251StringEncoding or NSISOLatin1StringEncoding .

The code is specifying the encoding NSUTF8StringEncoding but the string has a byte value that is not a valid UTF-8 character. Pick an encoding that matches the string.

Try an encoding such as NSISOLatin1StringEncoding :

8-bit ISO Latin 1 encoding.

NSMacOSRomanStringEncoding might be another encoding to consider if you are coming from a Mac environment.

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