字符串的两位数除法

Two digit division from string

本文关键字:两位 除法 字符串      更新时间:2023-10-16

我想划分一个字符串值,我得到。假设我有一组顾客。每个客户在一封信中都有几张纸。我有两个字符串变量:

sheetsPerCustomer和totalPagescustomer

当前是这样的:

Customer A:
sheetsPerCustomer = "01"  totalPagescustomer "06" // page 1 of 3
sheetsPerCustomer = "02"  totalPagescustomer "06" // page 2 of 3
sheetsPerCustomer = "03"  totalPagescustomer "06" // page 3 of 3

我必须除以totalPagescustomer,因为总页数是3而不是6。它应该看起来像这样:

sheetsPerCustomer = "01"  totalPagescustomer "03" // page 1 of 3
sheetsPerCustomer = "02"  totalPagescustomer "03" // page 2 of 3
sheetsPerCustomer = "03"  totalPagescustomer "03" // page 3 of 3

直接除法不起作用,因为如果我将字符串转换为int进行除法,"0"将丢失。我需要保持左边的总页数可以是10,20等,所以我需要两个数字。有办法存档吗?

避免麻烦,使用整数。它使你的意图更加清晰。如果你想使用类似于整型的东西,那么也许你应该使用整型。

如果你需要显示一个2位数的数字,你可以这样做:

std::cout << std::setfill('0') << std::setw(2) << sheetsPerCustomer  << std::endl;

这里有一个类似的方法:

#include <iostream>
using namespace std;
int main()
{
   char buf[16];
   int j = 7;
   sprintf(buf, "%02d", j);
   cout << "Result is " << buf << endl;
   return 0;
}

打印Result is 07