4

std::string からすべての整数を取得し、それらの各整数を int 変数に取得する際に助けが必要です。

文字列の例:

<blah> hi 153 67 216

プログラムで「blah」と「hi」を無視して、それぞれの整数を int 変数に格納するようにしたいと思います。したがって、次のようになります。

a = 153
b = 67
c = 216

次に、次のようにそれぞれを個別に自由に印刷できます。

printf("First int: %d", a);
printf("Second int: %d", b);
printf("Third int: %d", c);

ありがとう!

4

5 に答える 5

1
  • std::isdigit()文字が数字かどうかを調べるために使用します。スペースがなくなるまで、別の に段階的に追加しstringます。
  • 次にstd::stoi()、文字列を int に変換するために使用します。
  • clear()メソッドを使用して文字列の内容をクリアします。
  • 最初のステップに進む

ベース文字列の最後に達しないまで繰り返します。

于 2013-06-26T22:04:33.790 に答える
1

最初に文字列トークナイザーを使用する

std::string text = "token, test   153 67 216";

char_separator<char> sep(", ");
tokenizer< char_separator<char> > tokens(text, sep);

次に、取得する値の数が正確にわからない場合は、単一の変数を使用するのではなく、読み取る要素の数に適応できるa のa b cような配列を使用する必要があります。int input[200]std::vector

std::vector<int> values;
BOOST_FOREACH (const string& t, tokens) {
    int value;
    if (stringstream(t) >> value) //return false if conversion does not succeed
      values.push_back(value);
}

for (int i = 0; i < values.size(); i++)
  std::cout << values[i] << " ";
std::cout << std::endl;

必ず:

#include <string>
#include <vector>
#include <sstream>
#include <iostream> //std::cout
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
using boost::tokenizer;
using boost::separator;

ところで、C++ をプログラミングしている場合は、 の使用を避けprintfstd::cout

于 2013-06-26T22:41:52.660 に答える
0
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>

int main() {
    using namespace std;
   int n=8,num[8];
    string sentence = "10 20 30 40 5 6 7 8";
    istringstream iss(sentence);

  vector<string> tokens;
copy(istream_iterator<string>(iss),
     istream_iterator<string>(),
     back_inserter(tokens));

     for(int i=0;i<n;i++){
     num[i]= atoi(tokens.at(i).c_str());
     }

     for(int i=0;i<n;i++){
     cout<<num[i];
     }

}
于 2015-07-01T19:26:22.280 に答える
0

文字列の行を読み取り、そこから整数を抽出するには、

 getline(cin,str);
 stringstream stream(str);
 while(1)
  {
    stream>>int_var_arr[i];
    if(!stream)
          break;
    i++;
    }
   } 

整数は int_var_arr[] に格納されます

于 2017-07-17T11:30:24.897 に答える