user473973
user473973

Reputation: 711

Printing quotation mark not in whole std::string in C++ gives negative ASCII value?

I'm running into a problem when reading from a file. Here is some sample code:

std::for_each(vec.begin(), vec.end(), [&](std::string str1) {

    //... split the string up by spaces into vector "split"

    for (auto& str : split) {
        std::cout << str << "\n";
        std::cout << str[0] << "\n";
    }
});

So basically I print each element of split out on one line, and then print the first character. What I get is this:

“test test test
?

where the first line is the whole str, and the second line should be the first character. However, it prints a ? instead. Even using a std::string will give the same result:

for (auto& str : split) {
        std::cout << str << "\n";
        std::cout << std::string(1, str[0]) << "\n";
}

I'm using clang++ -std=c++11 as my setup. Has anyone else seen this?

Upvotes: 1

Views: 236

Answers (1)

Qaz
Qaz

Reputation: 61920

Your string is probably not encoded one element => one character. I was able to reproduce your issue here and it looks like the special quotation mark takes the first three string bytes, so this would print it properly:

std::cout << s.substr(0, 3);

Your situation could be a bit different, but I'm guessing it's UTF-8 for both you and Coliru. Specifically, the character looks to be this one, the "left double quotation mark", with a UTF-8 value of 0xE2809C.

Upvotes: 5

Related Questions