逗号格式化C ++中的数字 [英] Comma Formatting for numbers in C++

查看:105
本文介绍了逗号格式化C ++中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助,在用户输入的数字中添加逗号,一些指导或帮助将不胜感激。到目前为止,我有它存储前三个数字和最后六个数字,然后只是格式化它。

I'm needing help in adding commas to the number the user enters, some guidance or help would be appreciated. So far I have it where i store the first three digits and the last six digits and then simply format it.

#include<iostream>

using namespace std;
int main ( int argc, char * argv[] ) 
{
unsigned long long userInput;
int fthreeDigit;

cout << "Enter a long long number: " << endl;
cin >> userInput;

fthreeDigit = ( userInput / 1000 );
userInput %= 1000;

cout << "Your Number: " << fthreeDigit << "," << userInput << endl;
system("pause");
return 0;
 }


推荐答案

可能最容易理解的方式来获得每一千个数字与向量的帮助。

Here is the brute force but may be easiest to understand way to get every thousand digits with the help of a vector.

#include<iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main ( int argc, char * argv[] ) 
{
    long long userInput;
    int fthreeDigit;

   cout << "Enter a long long number: " << endl;
   cin >> userInput;
   vector <int> res;  //use vector to store every 3 digits
   while (userInput !=0)
   {
     fthreeDigit = userInput %1000;
     res.push_back(fthreeDigit);
     userInput = userInput / 1000 ;
   }

   std::reverse(res.begin(), res.end());
   for (size_t i = 0; i < res.size()-1; ++i)
   {
     if (res[i] ==0)
     {
        cout << "000"<<",";
     }
     else
     {
       cout << res[i] << ",";
     }
   }

   if (res[res.size()-1] == 0)
   {
       cout << "000";
   }
   else{
       cout << res[res.size()-1];
   }
   cout <<endl;
   cin.get();
   return 0;
}

我用下面的例子测试了这个代码:

I tested this code with the following case:

Input: 123456 Output: 123,456
Input: 12     Output: 12
Input: 12345  Output: 12,345
Input: 1234567 Output: 1,234,567
Input: 123456789 Output: 123,456,789
Input: 12345678 Output: 12,345,678

我想这是你想要根据你对评论的回应。

I guess this is what you want according to your response to comments.

这篇关于逗号格式化C ++中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆