在不使用字符串的情况下计算数字中的数字

时间:2014-03-18 00:20:08

标签: c++ string parsing numbers digits

我有下一个代码,要求用户提供一个非常长的数字,如100000000,然后它打印出一个给定数字出现在该数字上的次数,代码工作正常并且做的一切正确,但教授告诉我,我不必使用字符串或字符,但当代码询问用户的数字时,它必然需要一个字符串,我不知道如何修改它,我使用了gmp库

#include <iostream>
#include <stdio.h>
#include <gmp.h>
#define MAX 40

using namespace std;

void searchDigit(FILE *fd);
int NewNumber();

int main()
{
    FILE *fd;
    int otherNumber;
    string text;
    mpz_t num;
    do
    {
        if((fd = fopen("File.txt","w+"))!= NULL)
        {
            mpz_init(num);
            cout << "Give me the number: " << endl;
            cin >> text;
            mpz_set_str(num,text.c_str(),10);
            mpz_out_str(fd,10,num);
            fclose(fd);
            searchDigit(fd);
            otherNumber = NewNumber();
        }
        else
           cout << "Fail!!" << endl;
    }while(otherNumber);
    return 0;
}

void searchDigit(FILE *fd)
{
    int car,continue = 1,r;
    char answer,digit;
    if((fd = fopen("File.txt","r"))!= NULL)
    {
        do
        {
            r = 0;
            fseek(fd,0,SEEK_SET);
            cout << "What digit do you want to search? " << endl;
            cin >> digit;
            while((car = fgetc(fd))!= EOF)
            {
                if(car == digit)
                   r++;
            }
            cout << "The digit x=" <<digit<< " appears " << r << " times" << endl;
            cout << "Do you want to search any other digit? " << endl;
            cin >> answer;
            if(answer != 'S')
               continue = 0;
        }while(continue);
    }
    else
       cout << "Fail!!" << endl;
}

int NewNumber()
{
    char answer;
    cout << "DO you wish to work with a new number? " << endl;
    cin >> answer;
    if(answer == 'S' || answer == 's')
       return 1;
    else
       return 0;
}

提前致谢

1 个答案:

答案 0 :(得分:0)

取决于您的输入实际有多大......但是对于检索数字,您可以执行以下操作:

#include <iostream>
using namespace std;

typedef unsigned long long UINT64;

int main() {
    UINT64 i;
    std::cin >> i;
    while (i >= 1) {
        int digit = i % 10;
        std::cout << digit << " ";
        i /= 10;
    }
}

输入:18446744073709551614

输出:4 1 6 1 5 5 9 0 7 3 7 0 4 4 7 6 4 4 8 1