来自字符串的两位数除法

Two digit division from string

我想分配一个我得到的字符串值。可以说我有一组客户。每个客户都被设置为在一封信中有许多张纸。我有两个字符串变量:

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 等,所以我需要两位数字。有办法存档吗?

省去麻烦并使用整数。它使您的意图更加清晰。如果你想使用一些东西 'like' 一个 int 那么也许你应该使用一个 int。

如果您随后需要显示一个 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.