C++程序添加逗号以延长数字

C++ program to add commas to long the digits

本文关键字:数字 程序 添加 C++      更新时间:2023-10-16

CS106B 课程书中关于字符串的示例。程序的意义是从末尾每三位数字后面添加逗号。在输入的情况下,15000输出必须是15,000。如您所见,我忽略了比 4 短的数字。

/*
 * File: AddCommas.cpp
 * -----------------
 *
 */
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
/*Function prototypes*/
string addCommas(string digits);
/*Main program*/
int main(){
    while(true){
        string digits;
        cout << "Enter a number: ";
        getline(cin, digits);
        if (digits == "") break;
        cout << addCommas(digits) << endl;
    }
    return 0;
}
/*Function: addCommas
 *Usage: string addCommas(string digits)
 *---------------------------------------
 *Adds commas to long digits
 */
string addCommas(string digits){
    string result;
    if (digits.length() > 3){
        int t = 0;
        for(int i = digits.length() - 1; i >= 0; i --){
            result = digits[i] + result;
            t++;
            if(t%3 == 0){
                result = ',' + result;
            }
        }
        if(result[0] == ','){
            result.erase(0, 1);
        }
    } else {
        result = digits;
    }
    return result;
}

这对于初学者来说可能太高级了,但也许这没关系因为它只依赖于 2 个 std::string 方法。 准备好解释它是如何工作的!

//   out                    in: string of only digits
std::string digiCommaL(std::string s) 
{
   // insert comma's from right (at implied decimal point) to left
   int32_t sSize = static_cast<int32_t>(s.size()); // sSize MUST be int
   if (sSize > 3)
      for (int indx = (sSize - 3);  indx > 0;  indx -= 3)
         s.insert(static_cast<size_t>(indx), 1, ',')
   return(s);
}

我对这个例子的解决方案。我不得不添加一些额外的代码来避免这样的事情:,200,000 当字符串长度 %3==0 时发生