だから、私はCでこれを書いたので、sscanfはsをスキャンしますが、それを破棄してdをスキャンして保存します。したがって、入力が「Hello 007」の場合、Helloはスキャンされますが破棄され、007がdに格納されます。
static void cmd_test(const char *s)
{
int d = maxdepth;
sscanf(s, "%*s%d", &d);
}
だから、私の質問は、私はC + +で同じことをすることができますか?おそらくstringstreamを使用していますか?
匿名の文字列を実際に抽出することはできませんが、ダミーを作成して無視するだけで済みます。
#include
#include
// #include //see below
void cmd_test(std::istream & iss)//any std::istream will do!
{
//alternatively, pass a `const char * str` as the argument,
//change the above header inclusion, and declare:
//std::istringstream iss(str);
int d;
std::string s;
if (!(iss >> s >> d)) { /* maybe handle error */ }
//now `d` holds your value if the above succeeded
}
条件付きで入力すると、抽出が失敗する可能性があることに注意してください。エラーが発生した場合の処理は、あなた次第です。実際の関数がエラーを既に伝えている場合は、単にエラーを返すことができるかもしれませんが、C ++の例外は例外をスローすることです。
使用例:
#include
#include
int main()
{
cmd_test(std::cin);
std::ifstream infile("myfile.txt");
cmd_test(infile);
std::string s = get_string_from_user();
std::istringstream iss(s);
cmd_test(iss);
}