C++程序添加逗号以延长数字
C++ program to add commas to long the digits
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 时发生
相关文章:
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 用于检查数字是否有数字或可被该数字的值整除的程序
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 为什么当我输入较大的数字时,我的程序会到达文件末尾?
- 如何在C++程序中使用下标数字?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 如何在 WindowProc 处理程序中区分箭头键和数字键盘?
- 在 txt 文件中显示前两个数字的程序
- 在不添加进位的情况下添加数字的C++程序
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- 一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
- 每次运行此 c++ 程序时如何获得不同的数字?
- 程序 查找数字的重复
- 反转一个数字程序不起作用,为什么?
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 如何制作一个查找数字平方值的 c++ 程序
- 双精度数字程序意外值
- For循环-魔术数字程序
- 完全数字程序中的逻辑错误