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?
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.
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';
}
Related
Is there some way of forcing the user to enter a certain pattern when I request input?
For example, If I request they enter five numbers (xx x xx)
I was wondering maybe an array that I can enter my pattern into, then it be matched to the input, but not for value obviously.
I do not know how I would do this (if its possible).
I am a beginner, as you can tell, so I thought I would come here cause you would know. If this is not possible, how else can this be done?
You can write while loop where you'll enter your input while some condition is true.
while(std::cin >> input){
if (checkInput(input))
break;
}
Function checkInput will check your input and returns true if your input matches some requirements.
For matching patterns in string I use the regex functions from the standard library (https://en.cppreference.com/w/cpp/regex)
You can use this site to test regular expressions : https://regex101.com/
#include <cassert>
#include <regex>
bool is_valid_input(const std::string& input)
{
// (xx x xx) needs pattern "\(\d{2} \d \d{2}\)"
// in code you get even more backslashes
static std::regex rx{ "\\(\\d{2} \\d \\d{2}\\)" };
static std::smatch match;
return std::regex_match(input, match, rx);
};
int main()
{
const std::string good_input{ "(12 3 45)" };
const std::string bad_input{ "(x3 4 55" };
assert(is_valid_input(good_input));
assert(!is_valid_input(bad_input));
}
You should have a while loop checking the input and breaking when the input is the correct pattern you want.
#include <iostream>
#include <string>
using namespace std;
int main() {
char numbers;
cout << "Enter 5 numbers: ";
cin >> numbers;
while(!checkForValidPattern(numbers)) {
cout << "Try 5 numbers XXXXX : ";
cin >> numbers;
}
cout << "numbers = " << numbers << endl;
return 0;
}
Of course, you will have to create the validation function and it depends on your specific need.
Do you mean simply with the correct location of spaces? If so perhaps you could read the third character in the string and the 5th and if they are anything other than whitespace then reject it. Maybe something like
while (true) {
std::cout << "input: ";
std::string input;
std::cin >> input; // e.g. "12 3 45"
char const correct1 = input[2];
if (correct1 == ' ') {
break;
} else {
std::cout << "Incorrect pattern";
}
}
You would then do the same for the 5th character
This may be entirely incorrect but thats roughly what I would do.
I am pretty new to c++ and I am trying to make a program that prints out the number based on user input. But when you add a , it breaks the code since it is not part of integers. What should I do?
I made a simplified code because I want to do more with the integers:
#include <iostream>
using namespace std;
int main(){
int player_input;
cout << "Insert the number" << endl;
cin >> player_input;
cout << player_input;
return 0; //the code doesn't work if you add a comma in cin when you run such as "3,500"
}
Read the input in as a string:
std::string input;
std::cin >> input;
Remove the commas, using the erase-remove idiom:
input.erase(std::remove(input.begin(), input.end(), ','), input.end());
which from C++20 you can write like this:
std::erase(input, ','); // C++20
Convert the string to an int:
int player_input = std::stoi(input);
With <locale>, you might do:
#include <locale>
template<typename T> class ThousandsSeparator : public std::numpunct<T> {
public:
ThousandsSeparator(T Separator) : m_Separator(Separator) {}
protected:
T do_thousands_sep() const override { return m_Separator; }
std::string do_grouping() const override { return "\03"; }
private:
T m_Separator;
};
int main() {
ThousandsSeparator<char> facet(',');
std::cin.imbue(std::locale(std::cin.getloc(), &facet));
int n;
std::cin >> n;
// ...
}
Demo
I think #Jarod42 is on the right general track, but I don't think there's usually a good reason to define your own locale for this task. In most cases you're doing to have a pre-defined locale you can use to do the job. For example, this code:
#include <locale>
#include <iostream>
int main() {
std::cin.imbue(std::locale("en-US"));
int i;
std::cin >> i;
std::cout << i << "\n";
}
...let's me enter a number like 3,400, and it'll print it back out as 3400, to show that it read all of that as a single number.
In a typical case, you'd probably want to simplify things even a bit further by using a nameless locale (std::cin.imbue(std::locale(""));, as this will normally at least try to use a locale matching the what the operating system is configured for, so it would support an American entering 3,400, and (for example) a German entering 3.400 instead.
A string is a variable-length sequence of characters. Why does it receive anything and prints it out?
#include <iostream>
#include <string>
using namespace std;
int main (){
string word;
while (cin >> word){
cout << word << endl;
}
return 0;
}
In this program, we read into a string, not an int. How can I fall out of this while loop i.e hit an invalid input?
Reading into a string will not fail, all input is valid. You may add any validation you like once the string is read.
Your question is a little vague, but if you're asking how to end the loop you can do it with an end-of-file. On Linux this you can generate one from the console with Control-D, and on Windows with Control-Z plus Enter.
Because you are taking the input in a string and string is a sequence of characters .so it takes anything you input from the keyboard either it is number or alphabet or any special character .
How can I check for invalid input?
If you could define what you consider to be "invalid input" you can filter for it in one of the std::string helper methods. In your example you eluded to numbers not being strings... so if you want to do something with pure numbers...
#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main (){
string word;
while (cin >> word){
bool isNumber = (word.find_first_not_of("0123456789") == std::string::npos);
if (isNumber){
cout << "it's a number! " << word << endl;
}else{
cout << word << endl;
}
}
return 0;
}
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <string>
#include <iomanip>
#include <fstream>
#include <stdio.h>
using namespace std;
int main()
{
ifstream file;
string filename;
char character;
int letters[153] = {};
cout << "Enter text file name: ";
cin >> filename;
file.open(filename.c_str());
if (! file.is_open())
{
cout << "Error opening file. Check file name. Exiting program." << endl;
exit(0);
}
while (file.peek() != EOF)
{
file >> character;
if(!file.fail())
{
letters[static_cast<int>(character)]++;
}
}
for (int i = 0; i <= 153; i++)
{
if (letters[i] > 0)
{
cout << static_cast<char>(i) << " " << letters[i] << endl;
}
}
exit(0);
}
#endif
Hi everyone, my current code counts the frequency of each letter from a text file. However, it does not count the number of blank spaces. Is there a simple way to printout the number of blank spaces in a .txt file?
Also, how come when I'm trying to access a vector item, I run into a seg fault?
For example, if I use:
cout << " " + letters[i] << endl;, it displays a segfault. Any ideas?
Thank you so much.
By default, iostreams formatted input extraction operations (those using >>) skip past all whitespace characters to get to the first non-whitespace character. Perhaps surprisingly, this includes the extraction operator for char. In order to consider whitespace characters as characters to be processed as usual, you should alter use the noskipws manipulator before processing:
file << std::noskipws;
Don't forget to set it back on later:
file << std::skipws;
What if you're one of those crazy people who wants to make a function that leaves this aspect (or in even all aspects) of the stream state as it was before it exits? Naturally, C++ provides a discouragingly ugly way to achieve this:
std::ios_base::fmtflags old_fmt = file.flags();
file << std::noskipws;
... // Do your thang
file.flags(old_fmt);
I'm only posting this as an alternative way of doing what you're apparently trying. This uses the same lookup table approach you use in your code, but uses an istreambuf_iterator for slurping unformatted (and unfiltered) raw characters out of the stream buffer directly.
#include <iostream>
#include <fstream>
#include <iterator>
#include <climits>
int main(int argc, char *argv[])
{
if (argc < 2)
return EXIT_FAILURE;
std::ifstream inf(argv[1]);
std::istreambuf_iterator<char> it_inf(inf), it_eof;
unsigned int arr[1 << CHAR_BIT] = {};
std::for_each(it_inf, it_eof,
[&arr](char c){ ++arr[static_cast<unsigned int>(c)];});
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);++i)
{
if (std::isprint(i) && arr[i])
std::cout << static_cast<char>(i) << ':' << arr[i] << std::endl;
}
return 0;
}
Executing this on the very source code file itself, (i.e. the code above) generates the following:
:124
#:4
&:3
':2
(:13
):13
*:1
+:4
,:4
/:1
0:3
1:2
2:1
::13
;:10
<:19
=:2
>:7
A:2
B:1
C:1
E:2
F:1
H:1
I:3
L:1
R:2
T:2
U:1
X:1
[:8
]:8
_:10
a:27
b:1
c:19
d:13
e:20
f:15
g:6
h:5
i:42
l:6
m:6
n:22
o:10
p:1
r:37
s:20
t:34
u:10
v:2
z:2
{:4
}:4
Just a different way to do it, but hopefully it is clear that usually the C++ standard library offers up elegant ways to do what you desire if you dig deep enough to find whats in there. Wishing you good luck.
I have a C++ program which needs to take user input. The user input will either be two ints (for example: 1 3) or it will be a char (for example: s).
I know I can get the twos ints like this:
cin >> x >> y;
But how do I go about getting the value of the cin if a char is input instead? I know cin.fail() will be called but when I call cin.get(), it does not retrieve the character that was input.
Thanks for the help!
Use std::getline to read the input into a string, then use std::istringstream to parse the values out.
You can do this in c++11. This solution is robust, will ignore spaces.
This is compiled with clang++-libc++ in ubuntu 13.10. Note that gcc doesn't have a full regex implementation yet, but you could use Boost.Regex as an alternative.
EDIT: Added negative numbers handling.
#include <regex>
#include <iostream>
#include <string>
#include <utility>
using namespace std;
int main() {
regex pattern(R"(\s*(-?\d+)\s+(-?\d+)\s*|\s*([[:alpha:]])\s*)");
string input;
smatch match;
char a_char;
pair<int, int> two_ints;
while (getline(cin, input)) {
if (regex_match(input, match, pattern)) {
if (match[3].matched) {
cout << match[3] << endl;
a_char = match[3].str()[0];
}
else {
cout << match[1] << " " << match[2] << endl;
two_ints = {stoi(match[1]), stoi(match[2])};
}
}
}
}