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

标签 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;
}

提前致谢

最佳答案

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

#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

关于c++ - 在不使用字符串的情况下计算数字中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22468063/

相关文章:

swift - 如何在 swift 4 中获取子字符串?

csv - 由于某些字段中存在意外换行,SQL COPY INTO 无法解析 CSV。 ROWTERMINATOR 和 FIELDQUOTE 参数不起作用

C++纯虚方法内存管理问题

c++ - 调试断言失败! vector 下标超出范围 C++

c# - Regex.Replace 比使用 String.Contains 的条件语句慢得多

android - 解析字符串信息android?

C - 如何将 strtok() 返回的标记存储到 char 指针数组中?

xml - 防止 `xmlValue` 剥离 <br/> 标签

c++ - 带有 std::shared_ptr 的视觉泄漏检测器

c++ - 在 CArray 中赋值的简单方法