質問

    

この質問にはすでに回答があります:

         

Visual Studioで実行すると警告が表示され、Linuxでプログラムをビルドしようとするとコンパイルエラーが発生するため、整数を文字列に変換するitoa()に代わるものがあるかどうか疑問に思っていました。

役に立ちましたか?

解決

C ++ 11では、 std::to_string を使用できます。

#include <string>

std::string s = std::to_string(5);

C ++ 11より前のバージョンで作業している場合は、C ++ストリームを使用できます。

#include <sstream>

int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();

http://notfaq.wordpressから取得.com / 2006/08/30 / c-convert-int-to-string /

他のヒント

boost :: lexical_cast は非常にうまく機能します。

#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
    std::string foo = boost::lexical_cast<std::string>(argc);
}

考古学

itoaは、atoi標準関数を補完するように設計された非標準ヘルパー関数であり、おそらくsprintfを非表示にします(ほとんどの機能はsprintfの観点から実装できます): http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html

Cウェイ

sprintfを使用します。またはsnprintf。またはあなたが見つけるどんなツールでも。

<!> quot; onebyone <!> quot;で正しく述べられているように、一部の関数は標準に含まれていません。彼のコメントの1つでは、ほとんどのコンパイラが代替手段を提供します(たとえば、Visual C ++には独自の_snprintfがあり、必要に応じてsnprintfにtypedefすることができます)

C ++の方法。

C ++ストリームを使用します(現在のケースではstd :: stringstream(または廃止されたstd :: strstreamで、Herb Sutterの著書の1つで提案されているように、やや高速です)。

結論

C ++を使用しているため、希望する方法を選択できます。

  • 高速な方法(つまりCの方法)ですが、コードがアプリケーションのボトルネック(早すぎる最適化は悪意があるなど)であり、バッファオーバーランのリスクを回避するためにコードが安全にカプセル化されていることを確認する必要があります。

  • より安全な方法(C ++の方法など)、コードのこの部分が重要ではないことがわかっている場合は、誰かがサイズを間違えたためにコードのこの部分がランダムな瞬間に壊れないことを確認してくださいまたはポインター(昨日、私のコンピューター上で、実生活で起こります。誰かが<!> quot; cool <!> quot;と思ったためです。実際にそれを必要とせずに高速な方法を使用します)。

sprintf()を試してください:

char str[12];
int num = 3;
sprintf(str, "%d", num); // str now contains "3"

sprintf()はprintf()に似ていますが、文字列に出力します。

また、Parappaがコメントで言及したように、snprintf()を使用して、バッファオーバーフローの発生を停止することもできます(変換する数値が文字列のサイズに適合しない場合)。 :

snprintf(str, sizeof(str), "%d", num);

シーンの背後で、lexical_castはこれを行います:

std::stringstream str;
str << myint;
std::string result;
str >> result;

<!> quot;ドラッグイン<!> quot;をしたくない場合これを後押しするには、上記を使用するのが良い解決策です。

c ++で独自のiota関数を次のように定義できます。

string itoa(int a)
{
    string ss="";   //create empty string
    while(a)
    {
        int x=a%10;
        a/=10;
        char i='0';
        i=i+x;
        ss=i+ss;      //append new character at the front of the string!
    }
    return ss;
}

#include <string>を忘れないでください。

<!>#1057; ++ 11はこれを解決し、 std::to_stringを提供します。 。 また、boost::lexical_castは古いコンパイラ用の便利なツールです。

これらのテンプレートを使用します

template <typename T> string toStr(T tmp)
{
    ostringstream out;
    out << tmp;
    return out.str();
}


template <typename T> T strTo(string tmp)
{
    T output;
    istringstream in(tmp);
    in >> output;
    return output;
}

Boost.Format または FastFormat 、両方の高品質C ++ライブラリ:

int i = 10;
std::string result;

Boost.Format付き

result = str(boost::format("%1%", i));

またはFastFormat

fastformat::fmt(result, "{0}", i);
fastformat::write(result, i);

明らかに、どちらも単一の整数の単純な変換以上のことをしています

実際には、巧妙に作成された1つのテンプレート関数を使用して、何でも文字列に変換できます。このコード例では、ループを使用してWin-32システムにサブディレクトリを作成します。文字列連結演算子operator +は、ルートとサフィックスを連結してディレクトリ名を生成するために使用されます。サフィックスは、ループ制御変数iをC ++文字列に変換し、テンプレート関数を使用して、それを別の文字列と連結することにより作成されます。

//Mark Renslow, Globe University, Minnesota School of Business, Utah Career College
//C++ instructor and Network Dean of Information Technology

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream> // string stream
#include <direct.h>

using namespace std;

string intToString(int x)
{
/**************************************/
/* This function is similar to itoa() */
/* "integer to alpha", a non-standard */
/* C language function. It takes an   */
/* integer as input and as output,    */
/* returns a C++ string.              */
/* itoa()  returned a C-string (null- */
/* terminated)                        */
/* This function is not needed because*/
/* the following template function    */
/* does it all                        */
/**************************************/   
       string r;
       stringstream s;

       s << x;
       r = s.str();

       return r;

}

template <class T>
string toString( T argument)
{
/**************************************/
/* This template shows the power of   */
/* C++ templates. This function will  */
/* convert anything to a string!      */
/* Precondition:                      */
/* operator<< is defined for type T    */
/**************************************/
       string r;
       stringstream s;

       s << argument;
       r = s.str();

       return r;

}

int main( )
{
    string s;

    cout << "What directory would you like me to make?";

    cin >> s;

    try
    {
      mkdir(s.c_str());
    }
    catch (exception& e) 
    {
      cerr << e.what( ) << endl;
    }

    chdir(s.c_str());

    //Using a loop and string concatenation to make several sub-directories
    for(int i = 0; i < 10; i++)
    {
        s = "Dir_";
        s = s + toString(i);
        mkdir(s.c_str());
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

十分な長さの文字列を割り当ててから、snprintfを使用します。

最良の答え、IMOは、ここで提供される機能です:

http://www.jb.man.ac.uk /~slowe/cpp/itoa.html

多くのライブラリで提供される非ANSI関数を模倣しています。

char* itoa(int value, char* result, int base);

また、非常に高速で、-O3の下で最適化されます。c++ string_format()...またはsprintfを使用していない理由は、それらが遅すぎるからですよね?

すべてのstringstreamメソッド には、フォーマットのためのロケールオブジェクトの使用のロックが含まれることがあります。この は、複数のスレッドからこの変換を使用している場合に注意する必要があるかもしれません...

詳細については、こちらをご覧ください。 C++で指定された長さの文字列に数値を変換します

int number = 123;

stringstream = s;

s << number;

cout << ss.str() << endl;

高速で安全な整数から文字列への変換方法に興味があり、標準ライブラリに限定されない場合は、FormatIntメソッドをお勧めします。 / "rel =" nofollow "> C ++形式ライブラリ:

fmt::FormatInt(42).str();   // convert to std::string
fmt::FormatInt(42).c_str(); // convert and get as a C string
                            // (mind the lifetime, same as std::string::c_str())

整数から文字列への変換ベンチマーク Boost Karmaから、この方法はglibcのsprintfまたはstd::stringstreamよりも数倍高速です。 独立ベンチマーク

免責事項:私はこのライブラリの著者です。

この thread-safe 関数を少し前に書いたのですが、結果に非常に満足しており、アルゴリズムが軽量で無駄のないものであり、標準のMSVC _itoa()関数の約3倍のパフォーマンスがあると感じています。

ここにリンクがあります。 最適なBase-10のみitoa()関数?パフォーマンスは少なくとも10倍ですsprintf()の。ベンチマークは、次のように関数のQAテストでもあります。

start = clock();
for (int i = LONG_MIN; i < LONG_MAX; i++) {
    if (i != atoi(_i32toa(buff, (int32_t)i))) {
        printf("\nError for %i", i);
    }
    if (!i) printf("\nAt zero");
}
printf("\nElapsed time was %f milliseconds", (double)clock() - (double)(start));

呼び出し元のアドレス空間のバッファ内のどこかに結果がフローティング状態になる、呼び出し元のストレージの使用に関する愚かな提案がいくつかあります。それらを無視します。ベンチマーク/ QAコードが示すように、リストしたコードは完全に機能します。

このコードは、組み込み環境で使用するのに十分な無駄がないと思います。もちろん、YMMV。

Windows CE派生プラットフォームでは、デフォルトでiostreamはありません。そこに行く方法は、_itoa<>ファミリを使用することをお勧めします。通常は_itow<>です(とにかくほとんどの文字列はUnicodeであるため)。

上記の提案のほとんどは技術的にはC ++ではなく、Cソリューションです。

std :: stringstream の使用方法を調べます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top