Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma Formatting for numbers in C++

Tags:

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;
 }
like image 299
JL22 Avatar asked Sep 16 '25 10:09

JL22


1 Answers

Is this what you need? The locale will do this for you correctly.

#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;
  std::cout.imbue(std::locale(""));
  std::cout << userInput << std::endl;

  return 0;
}
like image 126
Nayana Adassuriya Avatar answered Sep 18 '25 23:09

Nayana Adassuriya