Reputation: 21
The code goes like this:
Input: Decimal number N, dot needs to be switched with notch, e.g. input: 0.36
output: 0,36
I have been thinking about it for a couple of hours already but can't figure how to solve it. Can someone help?
Upvotes: 1
Views: 1778
Reputation: 51815
You can do this by setting the locale for the cin
and cout
streams using the std::imbue()
function.
The following example uses the English/US (dot) decimal separator for input and the French (comma) for output; swapping the arguments for the two imbue
calls will reverse this.
#include <iostream>
#include <locale>
int main()
{
std::cin.imbue(std::locale("en_US")); // Set INPUT to use the DOT
std::cout.imbue(std::locale("fr_FR")); // Set OUTPUT to use a COMMA
double test;
std::cout << "Enter a number: ";
std::cin >> test;
std::cout << "Number was: " << test << std::endl;
return 0;
}
The std::locale
section of the C++ Standard Template Library provides numerous options for customising (and fine-tuning) numeric input/output formats, but the techniques it offers are not trivial to master.
Upvotes: 4
Reputation: 29945
You can read the number as text, and then use std::replace
:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string number;
std::cin >> number;
std::replace(number.begin(), number.end(), '.', ',');
std::cout << number << '\n';
}
Upvotes: 1