簡體   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