I checked many links on Stack and to other site. Most of it does it what is supposed to do, but not "exactly" how I want to. Here is the problem and the best solution that i found on online.
I want to enter a number, float for example and input should be checked if is a float or not.
I'm using this snippet found online. Also to mention that i need to repeat validation each time for loop its iterated.The "n" is entered separately before this function and its in "private".It does its job perfectly, except ...If you enter "55" (number), it checks and validates. That's ok.
If you enter "dfgfd" stuff (not a number), it checks and repeats question. That's ok.
If you enter "dfgdfgdg55",it checks and repeats question. It's also ok. If you enter "55dfgfd" stuff, it checks and NOT repeats. That's NOT OK.It just discarding characters after numbers.I want to discard this also.So correct input should be JUST "55" entered.(Number 55 is just a example number entered when prompted).Also I tried this on a simpler function "model".First to enter "55", second to enter "55gdf". They been presented on screen as "55" and "55". Then i added some code afterwards to compare these numbers. They are not the same!
#include <iostream>
using namespace std;
int Provera_kucanja()
{
cout<<endl;
cout<<"Input boundary for an array"<<endl;
cin>>n;
while (cin.fail() || !(n>0))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"You didnt entered number, please try again... "<<endl;
cin>>n;
}
cout<<endl;
return 0;
}
float Unos_brojeva()
{
cout<<"\n";
cout<<"Now you must enter number into array:\n "<<endl;
for (int i = 0; i < n ; i++)
{
cout<<"Input "<<"["<<i<<"]"<<" number in array: ";
float r;
cin>>r;
while (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"You didnt entered number, please try again... "<<endl;
cout<<"Input "<<"["<<i<<"]"<<" number in array: ";
cin>>r;
}
unos[i]=r;
}
cout<<endl;
cout<<"Now show unsorted array members: "<<endl;
for(int i = 0; i < n; i++)
{
cout<<"This is "<<"["<<i<<"]"<<" member of array named 'unos': "<<unos[i]<<endl;
}
cout<<"\n"<<endl;
cin.get();
return 0;
}
int main(){
Provera_kucanja();
Unos_brojeva();
}
On the down side using suggested answers is that when user enters something like "ghfg" , result of this conversion is a ZERO!. So suggested answers is no-go's.
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string A_number;
char* An_array=new char[A_number.length()];
cout<<"Enter value for A_number: ";
cin>>A_number;
strcpy(An_array,A_number.c_str());
float n=atof(An_array);
cout<<"Value entered is: "<<n;
cin.get();
return 0;
}
The line:
cin >> r
is going to try to read a valid float, even if there is bad trailing information after it.
You are saying the problem occurs when someone enters 55x, in this case you think it should not be considered a valid number.
There is an answer to your problem here: https://stackoverflow.com/a/19717896/312594
What you have to do is read the entire data in as a string and confirm that only characters that are possible as float input (digits, ., +, -, etc.) are in the input, and in the correct possible order. Only after you validate the input do you convert the input to float (via cin or some other mechanism).
In most cases you should accept 55x as 55 since that's probably what the user wants, but if you do want to be strict you have to perform the additional validation yourself.
p.s. - I almost hate to say this as I do not want to sound biased, but as you're learning C++ you may find it useful to write all of your code, including prompts, in English. If you later ask for help on StackOverflow, it will be easier for more people to understand what you are trying to do and therefore to help you out.
Sounds like you want to read in the input as strings (or possibly whole lines), and then you can test those strings any way you like.
Related
I am new to programming, started with C++ quite recently and I use CLion IDE.
I need to solve something, but I am not sure how exactly and I need your help with a basic C++ console program.
if the user enters a ten-digit number and the fifth number is one, the output should be this word - "zadochno".
if the user enters a ten-digit number and the fifth number is two, the output should be this word - "redovno".
The user is expected to enter 2101162235 or similar.
In any case, the fifth element should be either 1 or 2.
Examples:
Option 1: input> 2101162235 -> output string "zadochno"
Option 2: input> 2101262235 -> output string "redovno"
I am able to only partially create the program:
#include<iostream>
int number;
cout << "Please, enter number: ";
cin > number;
//I believe there should be an if statement or for loop here:
if(){
}
Can you please help me?
You can take the input from the user as std::string and then check if the element at index 4 is 1 or 2 as shown below:
#include <iostream>
#include <string>
int main()
{
std::string input;
//take input from user
std::getline(std::cin, input);
//check if the 5th letter(at index 4 since indexing starts with 0) is '1' or '2'
if(input.at(4) == '1')
{
std::cout<< "zadochno"<<std::endl;
}
else if(input.at(4) == '2')
{
std::cout << "redovno"<<std::endl;
}
//this below shown for loop is optional. If you're sure that the user input contains only digits then you can skip/remove this for loop.
for(int i = 0; i < input.size(); ++i)
{
//check if the all the characters are digits of a number
if(std::isdigit(input[i]))
{
;//std::cout<<"yes digit";
}
else
{
std::cout<<"Please enter a valid number"<<std::endl;
}
}
return 0;
}
The output of the above program can be seen here.
Assuming the user does enter a 10 digit number (ie you don't need to check if they enter eg "foo" or "bar3000"), you can do the following:
Read the input as a std::string, not as int. User input is a string of characters always. Only if you need it you can get it converted to an integer. You do not need it as int. The n-th character of a std::string called user_input is user_input[n]. You just need to check whether the character in the middle is either '1' or '2'.
If you do need to check that the user did enter digits, you could use std::isdigit.
First of all thanks for answering and helping out...
Now i was making a program to let the user enter any number... and then use the program to point out the total number of 4's in the the number entered and i have now encountered a problem..
This is my first post here so please excuse me if i make any mistakes..
The Code
int main()
{
int T,i,j,l;
char N,p[10];
cin>>T;
while(T--) //The number of times a user can enter a new number
{
cout<<"\nEnter Numbers\n";
l=0;i=0;
do
{
N=getch(); //getch is used so that the enter key need not be pressed and the
//number looks like a whole and also so the each number is
//individually stored
p[i]=N; //here the number entered is stored in p
cout<<N; //to display the number obviously
l++;i++;
}while(N!=' '); //Now here between '' something has to be present so that the loop
//terminates as soon as the enter key is pressed right now as soon
//as the spacebar is hit the loop will terminate.
cout<<"\n";
j=0;
for(i=0;i<l;i++) //using l so that the loop runs accordingly
{
if(p[i]=='4')
{
j++; //for couting the number of 4's
}
cout<<p[i]<<"\n"; //wont be needing in the final program but here cout is just
// to check the output
}
cout<<"\n THERE ARE "<<j<<" FOURS\n";
}
}
Please not that i already have a solution for my program so please DO NOT provide a different code using some different logic... i really need this very same program to work.i know that this program can be made to work using string length but here i want the loop to terminate after the enter key is pressed.
Well if you want to stop getting input when the user presses enter instead of space you need to test against '\r', '\n' or '\r\n' depending on what OS you are using. That said you really should be using standard C++ if you are going to use C++. You could easily make your code like:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
int loops;
std::cout << "How many numbers to check: ";
std::cin >> loops;
std::cin.get(); // eat newline
for (int i = 0; i < loops; i++)
{
std::string numbers;
std::cout << "Enter numbers and press enter: ";
std::getline(std::cin, numbers);
auto numberOf4s = std::count(numbers.begin(), numbers.end(), '4');
std::cout << "Number of 4's entered: " << numberOf4s << std::endl;
}
return 0;
}
Live Example
You can to see check if N is equal to '\r'. So your while loop looks like
do
{
N=getch(); //getch is used so that the enter key need not be pressed and the
//number looks like a whole and also so the each number is
//individually stored
p[i]=N; //here the number entered is stored in p
cout<<N; //to display the number obviously
l++;i++;
}while(N!='\r');
Good evening everyone, i am attempting to write code that will determine when a number is largest and smallest.. I have asked some tutors I know for help and they have been stumped on this as well. I can not use functions or arrays or breaks. :/ Which I understand makes the process more difficult.. My professor has stated
"The only decisions staments allowed inside the loop are to determine the largest and smallest value. This means you are not allowed to use a decision to determine if the first number was entered. This is going to require you to prime your loop. We cover priming the loop in the next section but for this assignment it means get the first number before the loop begins. We will also assume that at least one number is going to be input."
I don't understand how he expects us to do something we have not learned yet, but regardless.. This is how far I have gotten on the assignment..
We have to have the user input a value to determine how many values will be input...
I keep receiving an error message after I input how many values I would like to check,
"the variable "num" is being used without being initialized.." But num is in the int!!!
Then have the software basically identify the largest and smallest... Hopefully this makes sense to someone.. If you have any questions, or if I need to clarify anything please let me know, I will do so to the best of my ability..
#include <iostream>
using namespace std;
int main ()
{
int number;
int max=0;
int num;
int min=0;
{ cout << "How many numbers do you want to enter" ;
cin >> number;
for (int i=0; num!=number; i++)
{
cout<<"Enter a num "; /* This is where they are supposed to place in a number, press enter, another number, press enter, until their enter presses = number*/
cin>>num;
if (num>max)
max=num;
if (num<min)
min=num;
}
cout<<"largest number is: "<<max << endl;
cout<<"smallest number is: "<<min << endl;
}
}
This:
for (int i=0; num!=number; i++)
has undefined behavior, num doesn't have a value when this is first evaluated. You meant i != number (or, even better, i < number).
It would be better to use some other way of stopping, i.e. stop when a non-number is entered for instance.
Update: Just to clarify: there are other issues as well, such as min not being initialized in a way that make as many numbers as possible smaller than it. I would probably have gone for min = INT_MAX; or something like that. See <climits> for that constant.
int min=0;
you should change that to
int min=std::numeric_limits<int>::max();
Otherwise, the if the number you entered is greater than 0, it will not be assigned to min.
the variable "num" is being used without being initialized..
Give num a value, you have not given it a value before your loop starts. But that loop concept itself is wrong, try this.
for (int i=0; i < number; i++)
There is two problem in your code, first your min must be a great number like maximum integer, and the second is your for loop should loop on i. I commented lines that you need to change :)
#include <iostream>
#include <limits>
using namespace std;
int main ()
{
int number;
int max=0;
int num;
int min=std::numeric_limits<int>::max(); // change min to maximum integer possible in c++
{
cout << "How many numbers do you want to enter" ;
cin >> number;
//for (int i=0; num !=number; i++) change this line
for (int i=0; i<number; i++) //to this line
{
cout<<"Enter a num "; /* This is where they are supposed to place in a number, press enter, another number, press enter, until their enter presses = number*/
cin>>num;
if (num>max)
max=num;
if (num<min)
min=num;
}
cout<<"largest number is: "<<max << endl;
cout<<"smallest number is: "<<min << endl;
}
}
The point of this program is for the user to enter the grade of a certain amount of students up to 50, from a range of grades A,B,C,D, or F. At the end, the program is then supposed to show how many students got each grade. Whenever I test the following code, whatever I input for the for loop repeats every time, such that if I input for it to do the grades 3 students, whatever letter I enter for student 1 will be the same grade for every student, so if one student has an A, they all will have an A. I also have to use arrays for this program because it's for college. Sorry if there's not enough information, this is my first time posting.
#include<iostream>
#include<iomanip>
#include<string>
void gradeTotals();
using namespace std;
int x,z,a=0,b=0,c=0,d=0,f=0,i=0;
char grade[50];
int main()
{
cout<<"Please enter the number of students"<<endl;
cin>>x;
for (i=0;i<x;i++)
{
int y;
y=i+1;
cout<<"Please enter a letter grade of A,B,C,D, or F for student "<<y<<endl;
cout<<"All grades must be uppercase"<<endl;
cin>>z;
grade[i]=z;
gradeTotals();
}
}
void gradeTotals()
{
if (grade[i]=='A')
{
a++;
}
else if (grade[i]=='B')
{
b++;
}
else if (grade[i]=='C')
{
c++;
}
else if (grade[i]=='D')
{
d++;
}
else if (grade[i]=='F')
{
f++;
}
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
cout<<d<<endl;
cout<<f<<endl;
}
It looks like your if statements are not doing what you expect. For instance:
if (grade[i]='B')
{
// This code will *always* execute
}
You ought to be using the double equals == to compare a value, and a single equals = to assign a value.
(Edit after additional code change)
Inside the for-loop, you are trying to use cin to read in a single character. However, since the z is an integer, cin is looking for a valid integer, which does not happen to include 'A' or 'B', etc.
Perhaps you should try using a getline() or get().
The problem lies in having your input variable as an int, take in a char.
What happens is that when you perform cin >> z;, the character that was input by the user is recognized as an invalid input by the >> operator and therefore does not extract the character.
As such, z does not get any value, the character stays in the stream, and the >> operator continues to fail to extract the character until the loop ends.
Therefore, you can solve your problem by making your input variable a char instead.
Here's a link to help you better understand how to avoid such problems in the future.
Thank you for reading.
I have been given a task of inputting some student data, like
option 1: Enter student name and id.
option 2: input i.d (verify against student id - input option 1), input upto 10 grades for the student and then calculating the average and letter grade for the student
option 3: output the student name, id and letter grade.
The program has to be written in a Class like structure - with declared variables and functions in the structure.
I have also been given the task for entering the details of 3 students using the Class structure. For simplicity sakes for now I am just writing a program for one student.
The program compiles O.K
First specific encountered problem: When I select option 'I' the program lets me input the student name and that's it! - skips the id input for some reason and continues on.
The problem is that I have been using cin>>and also scanf() as my main input methods - but these and system("Pause") have not been serving me well - I understand system("pause") is not very efficient. In the past I have been advised to use a real string type to represent strings like std::string class from the <string> library.
I would therefore appreciate any help with string classes so I can learn of them.
I believe there may be some other problems with my program but any advice with the string classes thing and my 'first specific encountered problem' would helpful to start of with.
So I have written the following program to represent my answer.
#include <iostream>
#include <cstdio>
#include <math.h>
using namespace std;
struct classroom{
char name;
int student_id;
float grades[10];
int num_tests;
float average;
float letter_grade;
void enter_name_id(void);
void enter_grade(int);
void average_grades(int);
void letter_grades(void);
void output_name_id_grade(void);
};
void classroom::enter_name_id(){
cout<<"\n Please enter name of student: \n"<<"\n";
cin>>name;
cout<<"\n Please enter student i.d number: \n"<<"\n";
scanf("%d",student_id);
cout<<"\n"<<student_id;
system("PAUSE");
}
void classroom::enter_grade(int n_tests){
if(n_tests<=10){
cout<<"\n Please enter student test grade: \n"<<"\n";
cin>>grades[n_tests];
}
else{
cout<<"\n You have reached your max number of grades entered!!"<<"\n";
}
system ("PAUSE");
}
void classroom::average_grades(int n_tests){
float sum=0;
int i;
for(i=0;i<n_tests;i++){
sum =sum+grades[i];
}
average=sum/(float)n_tests;
system ("PAUSE");
}
void classroom::letter_grades(void){
if(average>=90){
letter_grade=65;
}
if(average>=80&&average<90){
letter_grade=66;
}
if(average>=70&&average<80){
letter_grade=67;
}
if(average>=60&&average<70){
letter_grade=68;
}
if(average<60){
letter_grade=70;
}
system ("PAUSE");
}
void classroom::output_name_id_grade(void){
cout<<"\ Name I.D Grade "<<"\n";
cout<<name <<" ";
cout<<student_id<<" ";
cout<<(char)letter_grade<<"\n";
system ("PAUSE");
}
int main()
{
classroom a;
char option,answer,ans;
int a_num_tests, id;
a_num_tests=0;
for( ; ;){
cout<<"\nEnter 'I' for Name and I.d, 'G' for grades or 'O' for Data output "<<"\n";
cin>>answer;
switch(answer){
case'I':
a.enter_name_id();
break;
case'G':
cout<<"\n Please enter student i.d number: "<<"\n";
scanf("%d",id);
cout<<"\n"<<id;
if(id==a.student_id){
a_num_tests++;
a.enter_grade(a_num_tests);
cout<<"\n Would you like to enter another grade? 'Y' or 'N': "<<"\n";
cin>>ans;
while(ans=='y'||'Y'){
a_num_tests++;
a.enter_grade(a_num_tests);
cout<<"\n Would you like to enter another grade? 'Y' or 'N': "<<"\n";
cin>>ans;
}
a.average_grades(a_num_tests);
a.letter_grades();
}
else{
cout<<"\n You have entered the wong i.d number!!! \n"<<"\n";
break;
}
case 'O':
a.output_name_id_grade();
break;
default:
cout<<"\n Wong Entry "<<"\n";
break;
}
}
system ("PAUSE");
return 0;
}
Hi again for all those whom want to know, this code worked for me:
void classroom::enter_name_id(void){
cout << " Please enter your name\n>";
std::cin.ignore( 25, '\n' );
cin.getline( name,25);
cout << " Type id\n>";
cin>>student_id;
return;
}
Not sure how this line works: 'std::cin.ignore( 25, '\n' );'!!!
But never the less it was needed in order to prevent the compiler skipping
the next line: 'cin.getline( name,25);'
Originally I had problems with just using 'cin>>name' in the class function and this is why I have asked the questions for alternative real string types.
If anyone has more to add to this question, please do so.
I would like to say thank you again to all my fans out there whom have contributed to this progress we have made together.
Sail on...
So many things to say... why would you write << "\n" << "\n"?? You can just put the entire string in one piece, << "\n\n"... anyway.
For input/output, just stick with iostreams, and don't mix and match C library functions without good cause. Perhaps like so:
std::string name;
int id;
std::cout << "Please enter your name: ";
std::getline(std::cin, name);
std::cout << "Please enter the ID: ";
std::cin >> id; // see below
Maybe this answer is of some use to you. The input operations should be checked for errors, if you want to write serious code.
Note that token extraction (>>) reads word by word, so std::cin >> name will only read one single word. For something like a name, we prefer getline() for that reason.
If you run your program from the command line, you won't need all those system("pause") calls, either...
Update: It's not generally a good idea to mix token extraction (>>) with line reading (getline()), since the former doesn't gobble up newlines while the latter does. Best to stick to just one of the two, whichever is more appropriate for the input format.
If you only use line reading, you still have to process each line, perhaps again by token extraction. To do so, you need a string stream. Include <sstream> and replace the last line by:
std::string line; // you can put this at the top with the other declarations
std::getline(std::cin, line);
std::istringstream iss(line);
iss >> id;
scanf causes buffer problem. You need to clear the buffer after using it.
fflush(stdin). this will clear your buffer and input will stop for id and other inputs.
Also you can use getch() instead of system ("PAUSE");