重複の可能性:
sscanf() の C++ 代替
次のコード行があります
sscanf(s, "%*s%d", &d);
を使用してこれを行うにはどうすればよいistringstream
ですか?
私はこれを試しました:
istringstream stream(s);
(stream >> d);
しかし、*s
inのため正しくありませんsscanf()
。
重複の可能性:
sscanf() の C++ 代替
次のコード行があります
sscanf(s, "%*s%d", &d);
を使用してこれを行うにはどうすればよいistringstream
ですか?
私はこれを試しました:
istringstream stream(s);
(stream >> d);
しかし、*s
inのため正しくありませんsscanf()
。
%*s
with は基本sscanf
的に、文字列 (空白までの任意の文字)を無視%*s
%d
することを意味し、その後は整数 ( ) を読み取るように指示しています。この場合、アスタリスク ( *
) はポインターとは関係ありません。
したがって、stringstream
s を使用して、同じ動作をエミュレートするだけです。整数を読み込む前に無視できる文字列を読み込みます。
int d;
string dummy;
istringstream stream(s);
stream >> dummy >> d;
すなわち。次の小さなプログラムを使用します。
#include <iostream>
#include <sstream>
using namespace std;
int main(void)
{
string s = "abc 123";
int d;
string dummy;
istringstream stream(s);
stream >> dummy >> d;
cout << "The value of d is: " << d << ", and we ignored: " << dummy << endl;
return 0;
}
出力は次のようになりますThe value of d is: 123, and we ignored: abc
。