3

だから私は文字列を整数に変換するために文字列ストリームを使いたい。

すべてが次のように行われると仮定します:

 using namespace std;

うまくいくと思われる基本的なケースは、私がこれを行うときです:

 string str = "12345";
 istringstream ss(str);
 int i;
 ss >> i;

それはうまくいきます。

ただし、次のように定義された文字列があるとしましょう。

string test = "1234567891";

そして私は:

int iterate = 0;
while (iterate):
    istringstream ss(test[iterate]);
    int i;
    ss >> i;
    i++;

これは私が望むように機能しません。基本的に、文字列の各要素を数値であるかのように個別に処理する必要があったため、最初にそれを int に変換したいのですが、それもできないようです。誰か助けてくれませんか?

私が得るエラーは次のとおりです。

   In file included from /usr/include/c++/4.8/iostream:40:0,
             from validate.cc:1:
/usr/include/c++/4.8/istream:872:5: note: template<class _CharT, class _Traits, class _Tp> std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&&, _Tp&)
 operator>>(basic_istream<_CharT, _Traits>&& __is, _Tp& __x)
 ^
/usr/include/c++/4.8/istream:872:5: note:   template argument     deduction/substitution failed:
validate.cc:39:12: note:   ‘std::ostream {aka std::basic_ostream<char>}’ is not derived from ‘std::basic_istream<_CharT, _Traits>’
cout >> i >> endl;
4

2 に答える 2

3

必要なものは次のようなものです:

#include <iostream>
#include <sstream>

int main()
{
    std::string str = "12345";
    std::stringstream ss(str);
    char c; // read chars
    while(ss >> c) // now we iterate over the stringstream, char by char
    {
        std::cout << c << std::endl;
        int i =  c - '0'; // gets you the integer represented by the ASCII code of i
        std::cout << i << std::endl;
    }
}

Live on Coliru

int c;代わりに の型として使用するとc、で読み取るのではなく、ss >> c整数全体を読み取ります。ASCIIをそれが表す整数に変換する必要がある場合は、次のように減算します12345charcharc'0'int i = c - '0';

編集@dreamlax がコメントで述べたように、文字列内の文字を読み取って整数に変換するだけの場合は、. を使用する必要はありませんstringstream。最初の文字列を次のように繰り返すことができます

for(char c: str)
{
    int i = c - '0';
    std::cout << i << std::endl;
}
于 2015-10-12T03:15:40.583 に答える