0

大規模なプログラムの一部として、数値の文字列を整数 (最終的には float) に変換する必要があります。残念ながら、キャストやアトイの使用は許可されていません。

私はこれに沿って簡単な操作を考えました:

void power10combiner(string deciValue){
   int result;
   int MaxIndex=strlen(deciValue);
        for(int i=0; MaxIndex>i;i++)
        {
          result+=(deciValue[i] * 10**(MaxIndex-i));
        }       
}

動作します。char を int に変換するにはどうすればよいですか? ASCII 変換を使用できると思いますが、とにかく char を int に追加することはできません (変換方法に、各 ASCII 番号の背後にある異なる数値を返す巨大な if ステートメントがあると仮定すると)。

4

4 に答える 4

2

これを行う方法はたくさんあり、関数に対して実行できる最適化と修正がいくつかあります。

1)関数から値を返さないため、戻り値の型はintになります。

2)const参照を渡すことにより、この関数を最適化できます。

次に例を示します。

std::stringstreamを使用して変換を行います。

int power10combiner(const string& deciValue)
{
    int result;

    std::stringstream ss;
    ss << deciValue.c_str();

    ss >> result;

    return result;
}

std::stringstreamを使用せずに変換を行います。

int power10combiner(const string& deciValue)
{
    int result = 0;
    for (int pos = 0; deciValue[pos] != '\0'; pos++)
        result = result*10 + (deciValue[pos] - '0');

    return result;
}
于 2012-04-07T23:11:35.150 に答える
0

私は std::stringstream を使用しますが、誰も strtol を使用したソリューションをまだ投稿していないので、ここに 1 つを示します。範囲外エラーの処理は実行しないことに注意してください。unix/linux では、errno変数を使用してそのようなエラーを検出できます (と比較することによりERANGE)。

ところで、浮動小数点数用の strtod/strtof/strtold 関数があります。

#include <iostream>
#include <cstdlib>
#include <string> 


int power10combiner(const std::string& deciValue){
   const char* str = deciValue.c_str();
   char* end; // the pointer to the first incorrect character if there is such
   // strtol/strtoll accept the desired base as their third argument
   long int res = strtol(str, &end, 10);

   if (deciValue.empty() || *end != '\0') {
       // handle error somehow, for example by throwing an exception
   }
   return res;
}

int main()
{
    std::string s = "100";

    std::cout << power10combiner(s) << std::endl;
}
于 2012-04-07T23:55:05.700 に答える
0

提案によって編集され、少し説明が追加されました。

int base = 1;
int len = strlen(deciValue);
int result = 0;
for (int i = (len-1); i >= 0; i--) { // Loop right to left. Is this off by one? Too tired to check.
    result += (int(deciValue[i] - '0') * base); // '0' means "where 0 is" in the character set. We are doing the conversion int() because it will try to multiply it as a character value otherwise; we must cast it to int.
    base *= 10; // This raises the base...it's exponential but simple and uses no outside means
}

これは、文字列が数字のみであることを前提としています。さらに明確にする必要がある場合は、コメントしてください。

于 2012-04-07T23:03:18.570 に答える
0

任意の基数に対して、位値システムを実装するだけで、文字列を反復的に解析して整数にすることができます。文字列が null で終了し、数字が符号なしであると仮定します。

unsigned int parse(const char * s, unsigned int base)
{
    unsigned int result = 0;
    for ( ; *s; ++s)
    {
        result *= base;
        result += *s - '0'; // see note
    }
    return result;
}

書かれているように、これは、実行文字セットで順番に配置されることが保証されている数字0、...、を使用した 10 までの基数に対してのみ機能します。9より大きな数の基数またはより自由な記号のセットが必要な場合*s - '0'は、指定された行を、入力文字の数字の値を決定する適切なルックアップ メカニズムに置き換える必要があります。

于 2012-04-07T23:13:57.900 に答える