繁体   English   中英

将数字转换为ascii,然后转换为int? C ++

[英]Convert digits to ascii, then an int? c++

如果我在一行上有单个字符,例如:4356如何将它们转换为最终整数? 因此,它将是4356,而不是“ 4”,“ 3”,“ 5”,“ 6”。所以,我知道我需要将第一个数字乘以10,再加上下一个数字,然后将所有数字乘以10,直到获得到达最后一个号码。 我如何以一种有效的,不会崩溃的方式编写它?

char chars[NUM_OF_CHARS] = { '4','5','8'};
int value = 0;

    for(int i=0;i<NUM_OF_CHARS;i++)
    {   
        if(chars[i] >= '0' && chars[i] <= '9') {
            value*=10;
            value+=chars[i] - '0';
        }
    }

并且,如果您的字符以空字符结尾的字符串,请在建议的注释中使用atoi()作为伙计。

使用C ++,您可以使用std::cin读取char ,检查它是否为数字,然后操作总数。

int total = 0;
char c;
while( std::cin >> c && c != '\n' )
{
   if( c >= '0' && c <= '9' )
       total = total * 10 + (c - 48);
}

std::cout << "Value: " << total << std::endl;

您可以读取类型为std :: string的对象中的输入,然后使用函数std::stoull (或std::stoi或该函数家族中的其他函数)

例如

std::string s;

std::cin >> s;

unsigned long long = stoull( s );

或者您可以简单地读入一些不可或缺的对象:)

例如,如果in_file是某些输入文件流,则可以编写

unsigned long long n;

while ( in_file >> n ) std::cout << n;

要么

std::vector<unsigned long long> v;
v.reserve( 100 );
unsigned long long n;

while ( in_file >> n ) v.push_back( n );

这是使用sringstream的示例:

#include <string>
#include <iostream>
#include <sstream>

int main()
{
    int n;
    std::string s ="1234";//or any number...
    //or: char s[] = "1234";
    std::stringstream strio;
    strio<<s;
    strio>>n;
    std::cout<<n<<std::endl;

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM