這聽起來像一個簡單的問題,但C++使它很難(至少對我來說):我有一個wstring,我想要第一個字母作爲wchar_t對象,然後從字符串中刪除第一個字母。C++如何獲得wstring的第一個字母
這這裏非ASCII字符不起作用:
wchar_t currentLetter = word.at(0);
因爲它返回字符,如德語變音兩個字符(在一個循環中)。
在這裏,這是不行的,或者:
wchar_t currentLetter = word.substr(0,1);
error: no viable conversion from 'std::basic_string<wchar_t>' to 'wchar_t'
而且也沒有這樣的:
wchar_t currentLetter = word.substr(0,1).c_str();
error: cannot initialize a variable of type 'wchar_t' with an rvalue of type 'const wchar_t *'
任何其他的想法?
乾杯,
馬丁
---- -----更新 下面是一些可執行的代碼應該說明問題。這一計劃將遍歷所有的字母和輸出一個他們一個:
#include <iostream>
using namespace std;
int main() {
wstring word = L"für";
wcout << word << endl;
wcout << word.at(1) << " " << word[1] << " " << word.substr(1,1) << endl;
wchar_t currentLetter;
bool isLastLetter;
do {
isLastLetter = (word.length() == 1);
currentLetter = word.at(0);
wcout << L"Letter: " << currentLetter << endl;
word = word.substr(1, word.length()); // remove first letter
} while (word.length() > 0);
return EXIT_SUCCESS;
}
然而,實際的輸出我得到的是:
量F r ? ? ? Letter:f Letter:? 信,R
源文件編碼UTF8和控制檯的編碼也被設置爲UTF-8。
第一個版本的問題究竟是什麼?你可以爲你的變音問題發佈代碼嗎? – nvoigt
C++字符串函數本質上並不支持Unicode。不要期望他們知道變音和變音的區別。 – chris
'wstring :: substr()'返回一個新的'wstring',而不是一個單獨的字符。 –