1

lets say I want the user to input a number and I want that number to cout with commas.

Example.

double attemptOne;

cout << "Enter a number: ";
cin >> attemptOne;  //user inputs 10000.25
cout << endl << attemptOne;  //I want to cout 10,000.25

I am new in c++ so please help me with out I am not talking about the decimal to be changed to a comma but for the program to know when the number is bigger than 999 to add commas like 1,000.25 10,000.25 100,000.25. I also do NOT want to use local

venom
  • 15
  • 8
  • Thousand-separator is usually part of the system region settings. – Some programmer dude Apr 05 '18 at 14:19
  • Hopefully the duplicate is sufficient. But if you want other formats, e.g. Indian separation like 1,23,456.78 then please pipe up. – Bathsheba Apr 05 '18 at 14:21
  • 2
    OP isn't asking about the decimal separator. He's asking about the thousands separator. The ',' in '1,000.25'. Though, it is still a duplicate. https://stackoverflow.com/questions/17530408/print-integer-with-thousands-and-millions-separator – evan Apr 05 '18 at 14:25
  • @Bathsheba The recent edit shows that the OP wants the thousands separator, not the decimal point. – Code-Apprentice Apr 05 '18 at 14:26
  • Oops. I'll reopen. Back in my box. – Bathsheba Apr 05 '18 at 14:26
  • 2
    Possible duplicate of [Print integer with thousands and millions separator](https://stackoverflow.com/questions/17530408/print-integer-with-thousands-and-millions-separator) – TioneB Apr 05 '18 at 14:27

1 Answers1

1

Maybe, since you need a string, you can read a string as well, and just parse it, adding commas every 3rd digit from the decimal point, or from the end if no decimal point exists:

#include <iostream>
#include <string>

int main()
{
    std::string attemptOne;
    std::cout << "Enter a number: ";
    std::cin >> attemptOne;

    size_t dec = attemptOne.rfind('.');
    if (dec == std::string::npos)
        dec = attemptOne.size();

    while (dec > 3)
        attemptOne.insert(dec -= 3, 1, ',');

    std::cout << attemptOne << std::endl;
}
Killzone Kid
  • 6,171
  • 3
  • 17
  • 37