How to limit cin to integers within the int data range? - c++

I am wondering how to only allow inputs for a cin which are within the int data range.
// This program counts the number of digits in an integer
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i, k;
cout << setw(20) << "Value Entered" << setw(20) << "Number of Digits" << endl;
while(1==1)
{
k = 1;
cout << setw(10) << "";
cin >> i;
while(i > 2147483647 || i < -2147483648)
{
cout << setw(10) << "";
cin >> i;
}
while( i / 10 > 0)
{
i = i / 10;
k++;
}
cout << setw(30) << k << endl;
}
return 0;
}
With the method I have it just gets stuck in the loop repeating 1.
EDIT:
Sample Output Format (Required)
"Value Entered" "Number of Digits"
14 2
225 3
-1000 4
Sample Output (What I have)
Value Entered Number of Digits
45
2
456
3
258
3
-2546
4

The extraction will fail if the number falls outside of the range for the type that it's being read into. When this happens the state of the stream will be set to failure, so you simply need to check for this state, and then reset the stream to a valid state:
while (!(cin >> i)) {
cin.clear();
cin.ignore(numeric_limit<streamsize>::max(), '\n');
}
clear() clears the error flags and ignore() puts the stream on a new line so that new data can be read. You may need to include <limits> for the code to work.
The condition for your second loop should be while (i > 0). As you had it you were off by one digit.

Related

char + int to change the char value

I am new to C++, learned it for more than a month. I have a beginner-level knowledge of Python, like creating a list, modifying it, loops, etc. I don't know some codes for C++ that I know in python.
I am making a program for a school class (creative program). This is a part of my code (description at the bottom):
int number, new_one, num_letter;
char one;
cout << "You chose to encypher a message\nPlease choose an integer between 1-25:";
cin >> number;
cout << "How many letters are in your word?";
cin >> num_letter;
if (num_letter == 1)
{
cout << "Enter the first letter";
cin >> one;
new_one = one + number;
cout << "Your encrypted message is '"
<< static_cast<char>(new_one)
<< "' with the code number of "
<< number;
I am making a program where it enciphers and deciphers a message. The user chooses the number of letters of their message (maximum of 10 because I don't know how to use a for-loop in C++ yet). Then, they choose an integer. Then, they enter the letter, hit Enter, enter the letter, and hit Enter for the number of letters in their message (I don't know how to separate strings to chars in C++ yet).
When the user enters their letter and hits Enter, I cin >> that letter into the variable one, which is a char. Then, I add that one to the number the user chose, so the ASCII code of the one increases by the value of the number.
For example, when I enter 3 for number and h for the value of one, 104 (the ASCII code of h) should add up with 3, resulting in 107, which I then would static_cast to a char value.
But, when I add h and 3, instead of creating 107, it creates 155. Same for other variables. I tried cout'ing static_cast<int>(one) (in this case, the letter h) and number (which is 3). They printed 104 and 3.
But, when I add those two values, it prints 155. Why is this happening?
This is my solution. Hope it helps!
#include <iostream>
using namespace std;
int main()
{
int offset = 0;
int num_with_offset;
int size;
// Gets offset from user
do{
cout << "You chose to encypher a message\nPlease choose an integer between 1-25: ";
cin >> offset;
} while (offset < 1 || offset > 25);
// Gets letters in word
do{
cout << "Letters in word: ";
cin >> size;
} while(size < 0);
// Given size, init arrays
int number[size];
char one[size];
// Conversion from char to int
for(int i = 0; i < (sizeof(one)/sizeof(one[0])); i++)
{
cout << "Enter character " << (i + 1) << ": ";
cin >> one[i];
num_with_offset = one[i] + offset;
// Converts ASCII to integer and stores it into array
number[i] = static_cast<int>(num_with_offset);
}
// Prints out the new encrypted message
for(int j = 0; j < (sizeof(number)/sizeof(number[0])); j++)
{
cout << "Your encrypted message is: "
<< number[j] << " , with the code number: "
<< offset << "." << endl;
}
cout << endl << endl;
return 0;
}

How can I take specific user inputs in an array?

I am coding a program that converts a binary number into decimal number by doubling (link to wikihow article).
If the user input is something other than 1 or 0, then its not a binary number, under that circumstance I want the loop to "break" and say something like:
"Oops! Binary numbers have only 1 or 0".
If not "then" the loop should continue.
That is I want to code something like
for(int digits = 0; digits != digitsINbinNum; ++digits){
if(a condition that checks if user input is anything else than 1 or 0){
coût << ""Oops! Binary numbers have only 1 or 0" << endl;
break;
}else{
cin >> binArray[digits];/*<-----------Here's the part where I am trying to do that*/
}
}
Refer to the code given below for more info:
#include <iostream>
#include <iterator>
using namespace std;
int main(){
int digitsINbinNum;
cout << "If you don't mind. Please enter the number of digits in your binary number: ";
cin >> digitsINbinNum;
int binArray[digitsINbinNum];
cout << "Enter the binary number: ";
for(int digits = 0; digits != digitsINbinNum; ++digits){
cin >> binArray[digits];/*<-----------Here's the part where I am trying to do that*/
}
/*using the doubling method as found in wikihow.com*/
int total = 0;
for(int posiOFdigit = 0; posiOFdigit != sizeof(binNum[noOFdigits]); posiOFdigit++){
total = total * 2 + binNum[posiOFdigit];
}
/*Printing the number*/
cout << "Decimal form of ";
for(int n = 0; n != noOFdigits; n++){
cout << binNum[n];
}
cout << " is " << total;
return 0;
}
The logic for converting a binary number into decimal number by the doubling method can be referred from the given link in the question.
Modifying the given code to keep it as close as possible to the question's reference code.
Note: As ISO C++ forbids variable length array, I am changing
int binArray[digits] to
int *binArray = (int *)malloc(sizeof(int) * digitsINbinNum);.
This modification makes it an integer pointer and it gets the memory of required size allocated at runtime.
#include <iostream>
using namespace std;
int main(){
int digitsINbinNum,
/* variable to keep decimal conversion of given binary */
decimal_val = 0;
bool is_binary = true;
cout << "If you don't mind. Please enter the number of digits in your binary number: ";
cin >> digitsINbinNum;
/*
ISO C++ forbids variable length array,
making it int pointer and allocating dynamic memory
*/
int *binArray = (int *)malloc(sizeof(int) * digitsINbinNum);
if (binArray == NULL)
{
cout << "Memory allocation failure" << endl;
exit -1;
}
cout << "Enter the binary number: ";
for(int digits = 0; digits != digitsINbinNum; ++digits){
cin >> binArray[digits];
/*<-----------Here's the part where I am trying to do that*/
/* doubling method logic for conversion of given binary to decimal */
if ((binArray[digits] == 0) ||
(binArray[digits] == 1))
{
decimal_val = (decimal_val * 2) + binArray[digits];
}
else /* not a binary number */
{
is_binary = false;
cout << "Oops! Binary numbers have only 1 or 0" << endl;
break;
}
}
/* if conversion is successful: print result */
if (is_binary)
{
cout << "Decimal Value for given binary is: " << decimal_val << endl;
}
if (binArray)
{
free(binArray);
}
return 0;
}
You don't need an array for this. Here is a simple solution:
#include <iostream>
int main(){
int digitsINbinNum;
std::cout << "If you don't mind. Please enter the number of digits in your binary number: ";
std::cin >> digitsINbinNum;
std::cout << "Enter the binary number: ";
int ret = 0;
for(int digits = 0; digits != digitsINbinNum; ++digits) {
int bin;
std::cin >> bin;
if (bin == 1 || bin == 0) {
ret = 2 * ret + bin;
} else {
std::cout << "Oops! Binary numbers have only 1 or 0" << std::endl;
return -1;
}
}
std::cout << ret << std::endl;
return 0;
}

cin a char into an int variable to stop a loop

I would like to read numbers into a static array of fixed size 10, but the user can break the loop by entering character E.
Here's my code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
cin >> myArray[i];
if (myArray[i] != 'E')
{
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
cout << count << endl;
system("PAUSE");
return 0;
}
However, I get the following results while entering E:
Enter upto 10 integers. Enter E to end
Enter num 1:5
5
Enter num 2:45
45
Enter num 3:25
25
Enter num 4:2
2
Enter num 5:E
-858993460
Enter num 6:-858993460
Enter num 7:-858993460
Enter num 8:-858993460
Enter num 9:-858993460
Enter num 10:-858993460
10
Press any key to continue . . .
How can I fix this code in the simplest way?
cin fails for parsing character 'E' to int. The solution would be to read string from user check if it is not "E" (it is a string not a single char so you need to use double quotes) and then try to convert string to int. However, this conversion can throw exception (see below).
Easiest solution:
#include <iostream>
#include <cmath>
#include <string> //for std::stoi function
using namespace std;
int main()
{
int myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
std::string input;
cin >> input;
if (input != "E")
{
try
{
// convert string to int this can throw see link below
myArray[i] = std::stoi(input);
}
catch (const std::exception& e)
{
std::cout << "This is not int" << std::endl;
}
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
cout << count << endl;
system("PAUSE");
return 0;
}
See documentation for std::stoi. It can throw exception so your program will end suddenly (by termination) that is why there is try and catch blocks around it. You will need to handle the case when user puts some garbage values in your string.
Just use:
char myArray[10];
because at the time of taking input console when get character then try to convert char to int which is not possible and store default value in std::cin i.e. 'E' to 0 (default value of int).
Use below code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
char myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
cin >> myArray[i];
if (myArray[i] == 'E')
{
break;
}
else
{
cout << myArray[i] << endl;
count++;
}
}
exitloop:
cout << count << endl;
system("PAUSE");
return 0;
}
Output:
Enter upto 10 integers. Enter E to end
Enter num 1:1
1
Enter num 2:E
1
sh: 1: PAUSE: not found
If you debug this, you will find all your myArray[i] are -858993460 (=0x CCCC CCCC), which is a value for the uninitialized variables in the stack.
When you put a E to an int variable myArray[i]. std::cin will set the state flag badbit to 1.
Then when you run cin >> myArray[i], it will skip it. In other words, do nothing.
Finally, you will get the result as above.
The problem is that attempting to read E as an int fails, and puts the stream in an error state where it stops reading (which you don't notice because it just doesn't do anything after that) and leaves your array elements uninitialized.
The simplest possible way is to break on any failure to read an integer:
for(int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
if (cin >> myArray[i])
{
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
If you want to check for E specifically, you need to read a string first, and then convert that to an int if it's not E.
As a bonus, you need to handle everything that's neither int nor E, which complicates the code a bit.
Something like this:
int count = 0;
string input;
while (cin >> input && count < 10)
{
if (input == "E")
{
break;
}
istringstream is(input);
if (is >> myArray[count])
{
cout << myArray[count] << endl;
count++;
}
else
{
cout << "Please input an integer, or E to exit." << endl;
}
}

how can i make the loop and change number to string

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int number=0;
cout<<"enter an number to cumpute";
cin>>number;
if(number=0)
cout<<"0"<<endl;
for(number>0;51>number;) {
number--;
cout<<"=";
}
for(number>10;number%10==0;) {
cout<<"|";
}
for(number>5;number%5==0;) {
cout<<"+";
}
cout<<endl;
system("PAUSE");
return 0;
}
(i got textbook called by Y.Daniel Liang. I can not find any thing like this) I have no idea how to make this loop work and I try use "while" and not working either. Should i just cout the "=" "+" "|", or start as string. I hope the output look like this.
BarPlot – A Simple Bar Graph Plotter:
Input a number in range [0 50] or a negative number to terminate:
| Enter Number: 6
| ====+> 6
| Enter Number: 12
| ====+====|=> 12
| Enter Number: 50
| ====+====|====+====|====+====|====+====|====+====> 50
| Enter Number: 53
| ERROR: 53 is not in acceptable range.
| Enter Number: 33
| ====+====|====+====|====+====|==> 33
| Enter Number: 0
| 0
| Enter Number: 5
| ====> 5
| Enter Number: -1
------------------------------------------------
BarPlot – End Plot by User Request
There is no need for you to convert a number to a string in order to solve the problem. The object cout can handle printing both numbers and strings without you needing to cast between them.
//example
int number = 1;
string str = "hello;
char c = '!';
//print hello1!
cout << str << number << c;
Here is a solution to the problem that does not require the need to cast an integer to a string.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
//output inital prompt
cout << "BarPlot – A Simple Bar Graph Plotter:\n";
cout << "Input a number in range [0 50] or a negative number to terminate.\n\n";
//read in input
int number = 0;
cout << "Enter Number: ";
cin >> number;
//continue asking for input until a negative number is given
while (number >= 0){
for (int i = 1; i < number; ++i){
//special symbol every 10th char
if (i % 10 == 0) cout << "|";
//special symbol every 5th char
else if (i % 5 == 0) cout << "+";
//every other char
else cout << "=";
}
//print 0 or the number with an arrow before it
if (number == 0) cout << 0;
else cout << "> " << number << "\n";
//re-ask for input
cout << "\nEnter Number: ";
cin >> number;
}
//output ending message
cout << "BarPlot – End Plot by User Request\n";
return EXIT_SUCCESS;
}

Sudoku input program skipping a prompt

I wrote a program for my computer science class that validates and solves sudoku puzzles from .txt files, but I wanted to take it one step further and write a program that made it easy to input and sudoku game. I'm sure you can figure out the format of the files based on this code. My only problem is that the last cin gets skipped, and that option is important to me. Any insight will be appreciated!!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct s {
s();
~s() {/*zzzz*/}
void show_grid();
void set (int &r, int &c, int &v) {g[r][c] = v;}
private:
int g[9][9];
};
//************************************************************************
void s::show_grid() {
//print game out to check it
cout << " | ------------------------------- |" << endl;
for (int k=0; k<81; k++) {
if (k%3 == 0)
cout << " |";
cout << " " << g[k/9][k%9];
if (k%9 == 8) {
cout << " |" << endl;
if ((k/9)%3 == 2)
cout << " | ------------------------------- |" << endl;
}
}
cout << endl;
}
//************************************************************************
s::s() {
//initialize all elements to zero
for (int i=0; i<9; i++) {
for (int j=0; j<9; j++) {
g[i][j] = 0;
}
}
}
//************************************************************************
void create_name (string &name) {
//append .txt extension LIKE IT OR NOT
string ext = name;
ext.erase(ext.begin(), ext.end() - 4);
if (ext.compare(".txt")!=0)
name.append(".txt");
}
//************************************************************************
int main () {
s g;
string name;
string yon("");
int count = 0;
int row, col, val, rcv;
ofstream os;
cout << "Enter game file name: ";
cin >> name;
create_name(name);
//open and do typical checks
os.open(name.c_str());
if (os.fail()) {
cerr << "Could not create " << name << ". Waaaah waaaaaaaaaah...\n\n";
return 0;
}
//useful output (hopefully)
cout << "Enter grid coordinates and value as a 3-digit number,\n"
<< "from left to right, row by row.\n"
<< "(e.g. 2 in first box would be 112)\n";
//take input as one int, to be user friendly
while (cin >> rcv && count < 81) {
row = (rcv / 100) - 1;
col = ((rcv / 10) % 10) - 1;
val = rcv % 10;
os << row << " " << col << " " << val << endl;
g.set (row, col, val);
count++;
}
os.close();
//From here down is broken, but it still compiles, runs, and works
cout << "Show grid input(y/n)?\n";
cin >> yon;
if (yon.compare("y")==0)
g.show_grid();
else if (yon.compare("n")==0)
cout << "Peace!\n";
return 0;
}
The problem is here:
while (cin >> rcv && count < 81)
Consider what happens when count==81: First, rcv will be input from cin, and only then the condition count < 81 will be evaluated to false. The loop will stop, and the value of rcv will be ignored. So effectively you read one input too many.
You should change the order of evaluation, so that count is checked first:
while (count < 81 && cin >> rcv)
Edit:
According to your comment above you are actually expecting to read less than 81 values. In that case, I recommend having the user input a special value (for example, 0) to terminate the loop. You'd just need to add if (rcv==0) break;. If you just input an invalid value as you are apparently doing, the cin stream will be put in a failed state and further input will not succeed.
Try something like:
//useful output (hopefully)
cout << "Enter grid coordinates and value as a 3-digit number,\n"
<< "from left to right, row by row.\n"
<< "(e.g. 2 in first box would be 112)\n"
<< "or Z to end the loop\n"; // 1
//take input as one int, to be user friendly
while (count < 81 && cin >> rcv ) { // 2
row = (rcv / 100) - 1;
col = ((rcv / 10) % 10) - 1;
val = rcv % 10;
os << row << " " << col << " " << val << endl;
g.set (row, col, val);
count++;
}
if(!std::cin) { // 3
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
1) Let the user know that he can enter in invalid char. It doesn't have to be Z, actually any non-numeric char will work.
2) Fix off-by-one error in the order of the &&.
3) If std::cin is in error state, clear the error and ignore the Z.
cin >> yon
still actually reads in a variable, it just reads in the variable that the while loop found to be false. When the while loop condition returns false rcv is ignored, so the number remains in the input stream waiting for the next cin statement. When yon is called that number meant for rcv is read into yon, giving you some strange errors.
it would be better to use interjay's method:
while (count < 81 && cin >> rcv)