c++ - 使用函数将字符串转换为整数

标签 c++

我是编程新手,我正在尝试让一个函数正常工作,将字符串转换为 int。我对这个函数的想法是收集字符串中的每个数字并将其存储在另一个字符串中,然后将其转换为一个 int。

函数返回值 0。

这个函数应该做的是返回转换后的数字。不应该为 0。

int getNumberFromString(int convertedNumber, string textToConvert)
{
    for (int i = 0; i < textToConvert.size(); i++)
    {
        string collectNumbers;
        int j = 0;
        if (textToConvert[i] == '1' || textToConvert[i] == '2' || textToConvert[i]   == '3' ||
            textToConvert[i] == '4' || textToConvert[i] == '5' || textToConvert[i] == '6' ||
            textToConvert[i] == '7' || textToConvert[i] == '8' || textToConvert[i] == '9' || textToConvert[i] == '0')
        {
            collectNumbers[j] = textToConvert[i];
            j++;
        }
        if (collectNumbers.size() == 0)
        {
            return false;
        }
        else if (collectNumbers.size() > 0)
        {

            stringstream convert(collectNumbers);
            if (!(convert >> convertedNumber))
            {
                convertedNumber = 0;
            }
            return convertedNumber;
        }
    }
}

最佳答案

也许你应该只使用库函数?

int stoi (const string&  str, size_t* idx = 0, int base = 10);

关于c++ - 使用函数将字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23207046/

相关文章:

c++ - node.js native 插件 - 包装类的析构函数不运行

枚举类型的 C++ 静态成员变量无法编译

c++ - 不完整类型模板构造函数声明的无效使用

c++ - 图案打印——我在这段 C++ 代码中哪里出错了?

c++ - 在父类(super class)构造函数中引用时调用哪个公共(public)函数?

c++ - BGL : bundled object without a default constructor?

C++ - 几何基元类层次结构

c++ - "The C++ compiler "/usr/bin/c++ "is not able to compile a simple test program."尝试安装 OpenCV 时

c++ - 为什么我不能在派生类重写函数中调用 protected 虚拟基类函数?

c++ - 索引和插入调用之间的 std::map 区别