C++ cin data limit? - c++

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.

Related

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++

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

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;
}

How do I record inputs within a for loop?

I'm attempting to make a program that asks for a class size that will define how many times the program asks for a test score.
Once it gets this it asks for the test score using a for loop until it reaches the class size.
What I want to do is record each score so that it can be announced at the end but I'm not sure how to record each seperate input within the code I am using. I want it to run something like:
Enter Score: 95
Enter Score: 25
Original Scores: 95,25
if the user entered the class size of 2. How do I do this? Maybe with an array but I dont know how to encorporate this?
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int size;
double score;
cout << "Enter class size <1-20> \n";
cin >> size;
for (int i = 0; 0 <= size; i++) {
cout << "Enter Score \n";
cin >> score;
}
return 0;
}
Just before the for loop, instantiate a std::vector<double> scores(size);. That is what you will use to record all the scores. (Write #include <vector> to bring in this functionality.)
Then fix the typos in your loop for (int i = 0; i < size; i++) {.
Then adjust the cin to cin >> scores[i];. (Isn't the C++ standard library clever?! Don't try to understand the mechanics behind that just yet - just accept the notation as plausible).
You can then iterate through that std::vector to output the scores. Lots of questions on this site to show you how to do that.
(Eventually you'll use a std::size_t as the type for the vector index rather than an int.)
You can do it just using a double array. Here is the code snippet.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int size;
double score[20]; // as size must me less than or equal 20
cout << "Enter class size <1-20> \n";
cin >> size;
for (int i = 0; i < size; i++) {
cout << "Enter Score \n";
cin >> score[i];
}
cout<<"Original Scores: ";
// Now iterate through all scores.
for(int i=0;i<size; i++){
if(i){
cout<<",";
}
cout<<score[i]
}
return 0;
}
Note: score size (20) is not checked.
It's possible to write even more compact code for reading values using range-for:
size_t sz;
std::cin >> sz;
std::vector<double> input(sz);
for(auto& el : input)
std::cin >> el;

Create object using user input

I want to create number of structure objects using input from user
for example:
I want to accept user value n and create n number of objects and pass these objects to a function where I initialize the variables to them.
#include <iostream>
#include<string>
#include "stdio.h"
using namespace std;
struct student
{
int roll_no;
char name[20];
};
void get_input(student p[],int n1)
{
for(int i=1;i<=n1;i++)
{
cout<<"Enter Roll Number ";
cin>>p[i].roll_no;
cout<<"\n Enter Name of the student: ";
cin>>p[i].name;
}
}
int main()
{
int n;
cout<<"How many student details would you want to enter: ";
cin>>n;
//Want to create number of object based on input n
student p[n];
get_input(student p[],n);
return 0;
}
There are a number of problems with your example.
The first problem is student p[n];. This is not strictly valid c++. Some compilers allow it as an extension. Without knowing which compiler you are using, and with what flags, I'll assume this is part of the problem. The typical solution for this problem is to use std::vector. An std::vector works in many ways like an array of variable size. std::vector<student> p(n); will create a vector named p containing n default constructed student objects.
The next problem is get_input(student p[],n);. It's unnecessary and incorrect to name the type when passing an argument. Just write get_input(p,n);. After all, you didn't specify that n is int when you called get_input. However, since p is an std::vector now, we need to add .data() to fetch a pointer to the actual data. It becomes get_input(p.data(), n);.
The final critical issue is the loop for (int i = 1; i <= n1; i++). Imagine n is 3. The values i will take are 1, 2 and 3. However, arrays are indexed starting at 0. If n is 3, you want to access the elements 0, 1 and 2. The correct loop is for (int i = 0; i < n1; i++).
These changes will allow your example to work but there are still many improvements that can be made.
#include <iostream>
#include <vector>
using namespace std;
struct student
{
int roll_no;
char name[20];
};
void get_input(student p[], int n1)
{
for (int i = 0; i < n1; i++)
{
cout << "Enter Roll Number ";
cin >> p[i].roll_no;
cout << "\n Enter Name of the student: ";
cin >> p[i].name;
}
}
int main()
{
int n;
cout << "How many student details would you want to enter: ";
cin >> n;
//Want to create number of object based on input n
std::vector<student> p(n);
get_input(p.data(), n);
return 0;
}
Consider using std::string instead of char name[20]. You won't have to guess how long a name might be, and you don't risk undefined behavior from having longer names.
struct student
{
int roll_no;
std::string name;
};
Consider passing p by reference, instead of using a pointer and size.
// Declaration / definition
void get_input(std::vector<student> & p)
// Usage
get_input(p);
Consider using a ranged based for loop instead of a regular for loop.
void get_input(std::vector<student> & p)
{
// for each student in p
for (student & s : p)
{
cout << "Enter Roll Number ";
cin >> s.roll_no;
cout << "\n Enter Name of the student: ";
cin >> s.name;
}
}
Use a vector of student: Here is some example code of how you can do it:
#include <iostream>
#include <string>
#include <vector>
#include "stdio.h"
using namespace std;
struct student
{ int roll_no;
char name[20];
};
void get_input(vector<student> & p1, int n1)
{
for (int i=0; i<n1; i++)
{
student s;
cout<<"Enter Roll Number: ";
cin>>s.roll_no;
cout<<"\n Enter Name of the student: ";
cin>>s.name;
p1.push_back(s);
}
}
int main()
{
int n;
cout<<"How many student details would you want to enter: ";
cin>>n;
//Want to create number of object based on input n
vector<student> p;
get_input(p, n);
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;
}