各文字を取得してチェックする必要がある文字列があります。
std::string key = "test"
int i = 0;
while (key.at(i))
{
// do some checking
i++;
}
これに伴う問題は、最終的にインデックスiが範囲外になるため、システムがクラッシュすることです。どうすればこれを修正できますか?
ありがとう!
std::string key = "test"
for(int i = 0; i < key.length(); i++)
{
//do some checking
}
for(auto i = key.cbegin(); i != key.cend(); ++i)
{
// do some checking
// call *i to get a char
}
このようなforループを使用できます。
#include <string>
std::string str("hello");
for(auto &c : str) {
std::cout << c << std::endl;
}
別の解決策はstd::for_each()
、次のように、各文字を処理するラムダ関数を使用して提供することです。
std::string key = "testing 123";
std::for_each(key.cbegin(), key.cend(), [](char c){ std::cout << c; });
これは印刷します:
testing 123