0

重複の可能性:
sscanf() の C++ 代替

次のコード行があります

sscanf(s, "%*s%d", &d);

を使用してこれを行うにはどうすればよいistringstreamですか?

私はこれを試しました:

istringstream stream(s);
(stream >> d);

しかし、*sinのため正しくありませんsscanf()

4

2 に答える 2

2

%*swith は基本sscanf的に、文字列 (空白までの任意の文字)を無視%*s%dすることを意味し、その後は整数 ( ) を読み取るように指示しています。この場合、アスタリスク ( *) はポインターとは関係ありません。

したがって、stringstreams を使用して、同じ動作をエミュレートするだけです。整数を読み込む前に無視できる文字列を読み込みます。

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

于 2011-10-29T01:11:18.627 に答える