あなたが本当に匿名の文字列に抽出することはできませんが、あなただけのダミーを作り、それを無視することができます
#include <string>
#include <istream>
// #include <sstream> // 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
}
注抽出ことあなたがエラーの場合にあなたがすることはあなた次第です。実際の関数がすでにエラーを通知している場合は、エラーをただちにreturn
にすることができますが、C++の例外は例外をスローすることです。
使用例:
#include <iostream>
#include <fstream>
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);
}
はたぶん 'istringstream'に'のconstのchar * 'からの引数の変化は少し重いのですか? –
+1はエラー処理に言及しています。 – ildjarn
@ChristianRau:誰かが知っている... OPはストリングストリームに関するケースにあるようだが、おそらく彼はすでにストリームがどこかにある。あなたが好きな場合は、 'const char *'で構築することはできません。私はコメントを追加しました。 –