C++: Just allow numbers as an input [duplicate] - c++

This question already has answers here:
How to make cin take only numbers
(2 answers)
Closed 2 years ago.
I want to block all the letters for input in the following code, can you help me with that?
#include <iostream>
using namespace std;
int main()
{
cout<<"To close this program you need to type in -1 for the first input"<<endl;
int m, n;
do{
int counter1 = 0;
int counter2 = 0;
cout<<"Now you need to input two seperate natural numbers, and after that it calculates the difference of both numbers factors!"<<endl;
cout<<"First Input"<<endl;
cin>>m;
if(m==-1){
break;
}
cout<<"Second Input"<<endl;
cin>>n;
if(m<0 or n<0){
cout<<"ERROR - Only natural numbers are allowed!"<<endl;
}
else{
...
The rest of the program is just the math.

When you declare a type of a variable, the variable can't contain anything else than what you have declared. So: You can’t use an int m to input a float. You could however use cin.ignore() (more details here) to accept a user input of "4.1" as "4". Here you go:
#include <iostream>
#include <limits>
using namespace std;
int main() {
cout << "Enter an int: ";
int m = 0;
while(!(cin >> m)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input!\nEnter an int: ";
}
cout << "You enterd: " << m << endl;
}

Related

C++ cin data limit?

So I took a C++ class in High School, but haven't done it in years, so I'm basically new. So I am wondering if there is a limit to the amount of cins you can do. It allows me to input 7 and then skips all the other inputs to go to the end. My guess is that there's a data limit. Is this correct?
#include <iostream>
using namespace std;
int main() {
int time1;
int time2;
int time3;
int time4;
int time5;
int time6;
int time7;
int time8;
int time9;
int time10;
cout<<"enter number";
cin>>time1;
cout<<"enter number";
cin>>time2;
cout<<"enter number 1";
cin>>time3;
cout<<"enter number 1";
cin>>time4;
cout<<"enter number 1";
cin>>time5;
cout<<"enter number 1";
cin>>time6;
cout<<"enter number 1";
cin>>time7;
cout<<"enter number 1";
cin>>time8;
cout<<"enter number 1";
cin>>time9;
cout<<"enter number 1";
cin>>time10;
cout<<"the end?";
}
You can use cins unlimited and you need to use loops. Here I provided example of fillind array buy cin.
#include <iosteam>
using namespace std;
int main(){
cout<<"Enter number of cins\n";
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cout<<"Enter "<<i<<" number\n";
cin>>a[i];
}
}
Your code should work fine if you only enter numbers. There is no limit to the amount of cins you can do. My guess is that you enter something that isn't a number, e.g. a string. When that happens cin's error flag is set and future attempts to get input will fail.
What you can do is add some input validation if you want. A simple if statement will do:
int num{0};
if (cin >> num)
{
....
}
If the input is not valid, i.e. the if condition is false, you need to clear the error:
cin.clear();
and discard everything remaining in the input buffer and newline:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You could use a std::vector to store the numbers instead of separate integer variables and use a do...while loop. Putting this all together your code could look like this:
#include <iostream>
#include <vector>
#include <limits>
int main()
{
std::vector<int> nums;
int n{0};
std::cout << "Enter total number to input" << std::endl;
std::cin >> n;
int i{0};
do
{
std::cout << "Enter number " << i+1 << std::endl;
int num{0};
if (std::cin >> num)
{
nums.push_back(num);
++i;
}
else
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input" << std::endl;
}
} while (i < n);
}
Note that I'm not using namespace std in my code. That's considered bad practice.

Undefined behaviour when entering `char` for integer variable with `std::cin`

I have this while loop, just to check if the entered number is 2. If the user entered by accident a letter instead of a number the loop goes to infinity even though I've added isdigit, but didn't fix the loop from going crazy if the input is a character. This is code:
int num1;
bool cond {false};
while(!cond){
cout<<"enter 2:";
cin>>num1;
if (!isdigit(num1)){
cout<<"not a digit:";
cin>>num1;
}
//
if(num1 == 2)
cond = true;
}
I would suggest trying something a little more straightforward instead of your current code:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int num1;
cout << "Please enter the number 2:";
cin >> num1;
while (num1 != 2)
{
cin.clear(); //Clears the error flag on cin.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "You did not enter the number 2, Please try again:";
cin >> num1;
}
return 0;
}
Now, cin.ignore(numeric_limits<streamsize>::max(), '\n'); is when it ignores up until '\n' or EOF \n is the delimiter meaning that, that is the character at which cin will stop ignoring.
Furthermore, numeric_limits<streamsize>::max() is basically saying there is no limit to the number of characters to ignore.
You need to use the header file #include<limits> to use this.
I recommend separating the reading of input data from converting it to a number. A good method for this is to use stringstream. Here's a working example:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int num1;
string input;
bool cond{ false };
cout << "enter 2:";
while (!cond) {
getline(cin, input);
stringstream ss(input);
ss >> num1;
if( ss.fail() ){
cout << "not a digit:";
continue;
}
//
if (num1 == 2)
cond = true;
else
cout << "enter 2:";
}
return 0;
}
int num1;
bool cond {false};
do{
cout<<"enter 2:";
cin>>num1;
if (cin.good()) {
cond = true;
}else {
cin.clear();
cin.ignore();
cout << "Invalid, please enter 2." << endl;
}
}while(!cond);
While false, execute statements. Also, if you want the user to re-enter a number, cin must be flushed.
Try declaring the variable num1 as char because isdigit(ch) works for char and not for int.
I hope this solves your problem
Why does the loop iterate infinitely?
Let's take this example
int a;
std::cin >> a;
std::cout << "Entered: " << a;
Now let's test it with different inputs
with int
5
Entered: 5
10
Entered: 10
Yes just as we would expect, but what happens when you enter a char?
with char
r
Entered: 0
f
Entered: 0
Why does this happen?
When you declare the variable int, and then do std::cin >> , you are telling the input method that the user will enter an integer, but when it doesn't get what it expected, it will fail. C++ will not implicitly convert the value of char into int. Hence, you get strange results.
How to solve this?
As I have mentioned earlier, it fails. When this fails you can catch it this way
if (!(std::cin >> a))
{
std::cout << "Invalid input ! \n";
}
We're saying, if the input fails, show the message.
let's test this new code.
int a;
if (!(std::cin >> a))
{
std::cout << "Invalid input !\n";
}
else
{
std::cout << "Entered: " << a;
}
5
Entered: 5
r
Invalid input !
How to print char value of the int?
If you want to just print the ASCII value of the entered number, you need to cast the value into char.
You can do
int num = 48;
char character_value = num;
Here C++ will implicitly convert char into int.
But if you need a safer type of conversion, prefer using static_cast<>.
The syntax looks like this
int a = 5;
char character_value = static_cast<char>(a);
Static cast in C++
Type casting in C++
Dealing with invalid input in C++

How to repeat the string in C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have to write a program in which integer value is entered from user and the string has to be displayed that many times. But I am getting errors.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int N;
cout << "Enter N: ";
cin >> N;
cout << string(N, "Well Done");
return 0;
}
Note: I am not permitted to use a loop in this assignment.
If you may not use a loop, you may use goto to get around the restriction:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int N;
cout << "Enter N: ";
cin >> N;
{
int i = 0;
goto test;
begin:
cout << "Well Done";
++i;
test:
if (i < N)
goto begin;
}
return 0;
}
Note that goto is widely considered bad practice.
EDIT2: IN THE ORIGINAL ASKER's COMMENTS, LOOPS OF ANY KIND ARE PROHIBITED IN THIS ASSIGNMENT.
Use recursion.
void printN(int n, string s) {
if (n <= 0) return;
cout << s << endl;
printN(n-1, s);
}
Then you can call this from your main program as follows:
printN(userInput, "Hi my name is ricky bobby");
EDIT: just saw you haven't learned recursion yet. Look up this term, and familiarize yourself with it. This is a way to do iteration without looping (this is the most simplistic way I can describe it)
std::string does not have a constructor that repeats a string N times (it does have one for repeating a single character N times, though). What you need is a loop instead, eg:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int N;
cout << "Enter N: ";
cin >> N;
for (int i = 0; i < N; ++i)
cout << "Well Done";
return 0;
}

Strings and Ints in C++

First off, this is for a homework assignment, so I'd appreciate help and guidance rather than just the answer in code.
The purpose of the code should be for a user to input a number and a width.
If the width is longer than the number, the number will be printed out with zeros in front of the number. For example 43 3 would give 043.
If the width isn't longer just the number would be printed: 433 2 would be 433.
I think I have to get the count of characters in the number and compare it to the count of characters in the width (if-else statement).
Then, if the number of characters in the number is more, print out the number. Else, print out the width.
I think I get the number of zeros by subtracting the length of the number from the length of the width. Then use that to set the number of zeros. Like I said this is homework and would rather learn than be given the answer.
If anyone can help, it'll be appreciated.
#include <iostream>;
#include <string>;
using namespace std;
string format(int number, int width) {
int count = 0;
if (number > width)// This if-else is incomplete
return ;
else
}
int main()
{
cout << "Enter a number: ";
string n;
cin >> n;
cout << "Enter the number's width: ";
string w;
cin >> w;
format(n, w);
}
no need to checking string or other things write these code C++ will do it for you automatically.
#include <conio.h>
#include <iostream>
using std::cout;
using std::cin;
#include <string>;
using std::string;
#include <iomanip>
using std::setw;
void format(int number, int width)
{
cout.fill('0');
cout << setw(width) << number;
}
int main()
{
cout << "Enter a number: ";
int n;
cin >> n;
cout << "Enter the number's width: ";
int w;
cin >> w;
format(n, w);
_getch();
return 0;
}

C++ Writing simple coin flip game

I'm writing a code for a game that prompts the user to pick how many times they want to flip a coin and guess how many times it will land on heads. I wrote most of, just need help finishing it up. I tried to include a count of the heads but ran into problems.
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int myRandNumGen(){
int num = rand();
return num;
}
char coinTossFunction( ){
char coinToss;
int coinTossValue = (myRandNumGen()%2); // 0 or 1
switch (coinTossValue) {
case 0:
coinToss = 'H';
break;
case 1:
coinToss = 'T';
break;
default:
break;
}
return coinToss;
}
int calcCoin(int n){
int cout_heads=0;
for(int i=0;i<=n;i++){
if(coinTossFunction() == 'H')
++cout_heads;
}
return (cout_heads/n);
}
int main(){
int coinflips, guess;
cout << "How many times do you want to flip the coin? " << endl;
cin >> coinflips;
cout << "Guess how many times a coin will land on heads if flipped: " << endl;
cin >> guess;
if (guess>coinflips) {
cout << "Guess Error";
}
for(int i=1;i<=coinflips;i++){
cout << calcCoin;
}
Here are a few problems with your code:
for(int i=0;i<=n;i++)
This will make i take the values from 0 to n, which means you will enter in the loop n+1 times, instead of n times.
return (cout_heads/n);
Since both variables cout_headsand n are integers, this will perform an integer division, and not a floating point division. The result will always be 0 or 1 in this case.
cout << calcCoin;
When you call a function you need to put parenthesis. Also your calCoin function takes a parameter.