【问题标题】:Change from string to number in C++ [closed]在 C++ 中从字符串更改为数字 [关闭]
【发布时间】:2014-03-31 21:05:19
【问题描述】:

有时需要处理字符串。通常需要从字符串更改为数字,或者相反。在 Pascal 中,我使用“str(n,st);”和“val(st, n, c);”,通常。请写下你的方法,如何在 C++ 中做到这一点(如果可以,请指定库)。

【问题讨论】:

标签: c++ string


【解决方案1】:

在 C++ 11 中有一组函数可以将 arithmetic types 的对象转换为 std::string 类型的对象

string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

还有一组函数将std::string类型的对象转换为arithmetic types的对象:

int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);

还有其他一些我没有在此处列出的执行 sich 转换的函数。例如,其中一些是处理字符数组的 C 函数。

【讨论】:

    【解决方案2】:

    使用std::stoi

    std::string example = "21";
    int i = std::stoi(example);
    

    查看此答案以获取更多信息 c++ parse int from string

    【讨论】:

      【解决方案3】:
      std::istringstream is("42");
      int answer;
      is >> answer;
      
      std::ostringstream os;
      os << 6*9;
      std::string real_answer = os.str();
      

      【讨论】:

        【解决方案4】:

        两种解决方案:

        解决方案 1:

        string strNum = "12345";
        int num = atoi(strNum.c_str());
        cout<<num<<endl;
        

        解决方案 2:

        #include <string>
        #include <sstream>
        #include <iostream>
        using namespace std;
        
        string strNum = "12345";
        istringstream tempStr(strNum);
        int num;
        tempStr >> num;
        cout<<num<<endl;
        

        【讨论】:

          猜你喜欢
          • 2021-03-12
          • 2013-06-23
          • 2018-02-12
          • 2013-09-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多