C ++手动将字符串转换为int吗? [英] C++ manually Convert string to int?

查看:46
本文介绍了C ++手动将字符串转换为int吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图手动将字符串转换为int,但遇到了困难.我首先检查输入的字符串是否为整数.接下来,我想在不使用任何库方法的情况下将该字符串转换为整数.

I was trying to manually convert a string to an int, and I have had difficulties. I first check to see if the string entered is an integer. Next, I want to convert that string to an integer without using any library methods.

当我在循环中逐行运行代码时,它执行了我需要的操作,但是当我在循环中运行时,它吐出了不正确的二进制结果.

When I ran the code inside my loop line by line, it did what I needed it to, but when I ran it inside a loop, it spat out incorrect binary results.

==>我要检查您输入的值是否是数字.

==> I am going to check if the value you enter is a number.

==>输入数字:234

==> Enter a number: 234

==>输入结果:1

==> Input result: 1

==>按Enter继续...

==> Press enter to continue...

==> 11001

==> 11001

// Darian Nwankwo, Random Programs, August 2, 2015

#include <iostream>
#include <string>
#include <cmath>

int main(int argc, const char * argv[]) {
    std::string number = "";
    bool isNumber = false;

    std::cout << "I am going to check if the value you enter is a number." << std::endl;
    std::cout << "Enter a number: ";
    std::cin >> number;
    std::cin.ignore();

    // Iterate through variable number to check if it is a number
    for ( int i = 0 ; i < number.length() ; i++ ) {
        if ( number[i] < 48 || number[i] > 57) {
            break;
        } else {
            isNumber = true;
        }
    }

    std::cout << "Input result: " << isNumber << std::endl;

    int newNumber = 0;             
    // Iterates over the number string variable and converts value to an integer
    if (isNumber) {
        for ( int i = 0 ; i < number.length() ; i++ ) {
            // newNumber += std::pow( 10.0, number.length() )
            newNumber = std::pow(10.0, ( number.length() - ( i + 1 ) ) * ( number[i] - '0' ));
        }
    } else {
        std::cout << "Can't convert." << std::endl;
    }

    char cont;
    std::cout << "Press enter to continue..." << std::endl;
    std::cin.get(cont);
    std::cout << newNumber;

    return 0;
}

推荐答案

将for循环更改为:

    for ( int i = number.length() -1 ; i >= 0 ; i-- ) {
        int power = number.length() - i -1;
        newNumber += (std::pow( 10.0,  power) * (number[i] - '0'));

并使newNumber翻倍.

and make newNumber to double.

希望有帮助!

这篇关于C ++手动将字符串转换为int吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆