[FAQ update C++11] Einmal Zahl nach String und zurück



  • http://www.c-plusplus.net/forum/39488

    Der Eintrag sollte vielleicht die Neuerungen aus C++11 erwähnen. Also Zahl ➡ String mit std::to_string und String ➡ Zahl mit std::stoi/stol/stoll/stoul/stoull/stof/stod/stold

    Beispiele

    #include <string>
    #include <iostream>
    using namespace std;
    
    int main() {
      // double -> string
      {
        double const d = 0.5;
        string s = to_string(d);
        cout << s << endl;
      }
    
      // int -> string
      {
        int const i = 10;
        string s = to_string(i);
        cout << s << endl;
      }
    
      // string -> int (dezimal)
      {
        string const s = "10";
        int i = stoi(s);
        cout << i << endl;
      }
    
      // string -> int (hex)
      {
        string const s = "0x10";
        int i = stoi(s, nullptr, 16);
        cout << i << endl;
      }
    
      // string -> double
      {
        string const s = "0.5";
        double d = stod(s);
        cout << d << endl;
      }
    
      // Enderkennung
      {
        string const s = "10keinezahl";
        size_t n;
        int i = stoi(s, &n);
        cout << i << endl;
        if(n != s.size()) {
          cout << n << " Zeichen als Zahl erkannt. Übrig: '" << s.substr(n) << "'\n";
        }
      }
    }
    


  • Habs übernommen, danke für die Mühe 🙂


Anmelden zum Antworten