C++ parse int from string [duplicate]

to pytanie ma już odpowiedzi tutaj : Zamknięte 10 lat temu .

Możliwy duplikat:
Jak przetworzyć ciąg znaków do int w C++?

Zrobiłem kilka badań i niektórzy mówią, aby użyć atio i inni mówią, że jest źle, a ja i tak nie mogę go uruchomić.

Więc po prostu chcę zapytać flat out, jaki jest właściwy sposób, aby przekonwertować ciąg znaków do int.

string s = "10";
int i = s....?
Dzięki!
Author: Community, 2010-12-14

5 answers

  • W C++11 użyj std::stoi as:

     std::string s = "10";
     int i = std::stoi(s);
    

    Zauważ, że std::stoi rzuci wyjątek typu std::invalid_argument, jeśli konwersja nie może być wykonana, lub {[6] } jeśli konwersja spowoduje przepełnienie(tzn. gdy wartość ciągu znaków jest zbyt duża dla typu int). Możesz użyć std::stol lub std:stoll chociaż w przypadku int wydaje się zbyt mały Dla ciągu wejściowego.

  • W C++03/98 można użyć dowolnego z poniższych:

     std::string s = "10";
     int i;
    
     //approach one
     std::istringstream(s) >> i; //i is 10 after this
    
     //approach two
     sscanf(s.c_str(), "%d", &i); //i is 10 after this
    

Zauważ, że powyższe dwa podejścia zawiodłyby dla input s = "10jh". Zwrócą 10 zamiast powiadamiania o błędzie. Tak więc bezpieczne i solidne podejście polega na napisaniu własnej funkcji, która przetwarza ciąg wejściowy, i zweryfikować każdy znak, aby sprawdzić, czy jest cyfra, czy nie, a następnie działać odpowiednio. Oto jedna solidna implementacja (choć niesprawdzona):

int to_int(char const *s)
{
     if ( s == NULL || *s == '\0' )
        throw std::invalid_argument("null or empty string argument");

     bool negate = (s[0] == '-');
     if ( *s == '+' || *s == '-' ) 
         ++s;

     if ( *s == '\0')
        throw std::invalid_argument("sign character only.");

     int result = 0;
     while(*s)
     {
          if ( *s < '0' || *s > '9' )
            throw std::invalid_argument("invalid input string");
          result = result * 10  - (*s - '0');  //assume negative number
          ++s;
     }
     return negate ? result : -result; //-result is positive!
} 

To rozwiązanie jest nieco zmodyfikowaną wersją mojego innego rozwiązania.

 103
Author: Nawaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-31 16:42:30

Możesz użyć boost:: lexical_cast :

#include <iostream>
#include <boost/lexical_cast.hpp>

int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;

   try   {
      i = boost::lexical_cast<int>( s1 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   try   {
      i = boost::lexical_cast<int>( s2 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   return 0;
}
 13
Author: Eugen Constantin Dinca,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-14 18:31:09

Nie ma "właściwej drogi". Jeśli potrzebujesz uniwersalnego (ale nieoptymalnego) rozwiązania, możesz użyć boost::lexical cast.

Powszechnym rozwiązaniem dla C++ jest użycie std::ostream i << operator. Możesz użyć metody stringstream i stringstream::str() do konwersji na string.

Jeśli naprawdę potrzebujesz szybkiego mechanizmu (zapamiętaj regułę 20/80), możesz poszukać "dedykowanego" rozwiązania, takiego jak C++ String Toolkit Library

Pozdrawiam,
Marcin

 9
Author: Marcin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-29 07:13:39

Możesz użyć istringstream.

string s = "10";

// create an input stream with your string.
istringstream is(str);

int i;
// use is like an input stream
is >> i;
 8
Author: Sanjit Saluja,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-29 07:13:52

Niektóre przydatne szybkie funkcje (jeśli nie używasz Boost):

template<typename T>
std::string ToString(const T& v)
{
    std::ostringstream ss;
    ss << v;
    return ss.str();
}

template<typename T>
T FromString(const std::string& str)
{
    std::istringstream ss(str);
    T ret;
    ss >> ret;
    return ret;
}

Przykład:

int i = FromString<int>(s);
std::string str = ToString(i);

Działa dla wszystkich typów strumieniowych (pływaków itp.). Będziesz musiał #include <sstream> i ewentualnie również #include <string>.

 5
Author: AshleysBrain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-14 18:28:24