I am trying to create a students program but it stops after I put the 4th name, it doesn't allow me to put the grades neither shows the list at the end...
#include<iostream>
using namespace std;
int main()
{
string name[4];
double g1[4],g2[4],avg[4];
int cont;
for(cont=1;cont<=4;cont++)
{
cout<<"STUDENT "<<cont<<"\n";
cout<<"Name: ";
cin>>name[cont];
cout<<"First Grade: ";
cin>>g1[cont];
cout<<"Second Grade: ";
cin>>g2[cont];
avg[cont]=(g1[cont]+g2[cont])/2;
}
cout<<"STUDENTS LIST"<<"\n";
cout<<"--------------"<<"\n";
for(cont=1;cont<=4;cont++)
{
cout<<name[cont]<<" "<<avg[cont]<<"\n";
}
}
string name[4]; is an array with 4 elements. Valid indices are 0,1,2 and 3. Your loops skips the first element and accesses the array out-of-bounds on the last iteraton. That causes undefined behavior. Anything could happen.
The two loops for(cont=1;cont<=4;cont++) is wrong because you can only use indice 0, 1, 2, 3 for 4-element arrays.
You should use for(cont=0;cont<4;cont++) instead and change cout<<"STUDENT "<<cont<<"\n"; to cout<<"STUDENT "<<(cont+1)<<"\n";.
Another option is to add one more elements to each arrays. First elements of the arrays won't be used then, but this may contribute for readability for you.
Related
New to c++. I want to take the input values in scoreCurrent and place them into different arrays depending on whether they're above the average or below the average. I tried looking for solutions from different websites and youtube but none worked so far. How do I do this?
I apologize if my whole code is a mess and thank you in advance.
#include <iostream>
using namespace std;
int main()
{
// student count
int students, upperLimit;
cout<<"Enter no. of students: ";
cin>>students;
// upper limit
do
{
cout<<"Enter the upper limit: ";
cin>>upperLimit;
if(upperLimit<5)
{
cout<<"Invalid upper limit."<<endl;
continue;
}
break;
}while(true);
// student scores
int scoreCurrent, scoreTotal;
float average=0;
int belowAve(students), aboveAve(students);
for(int index=1; index<=students; index++)
{
cout<<"Enter score for student no. "<<index<<": ";
cin>>scoreCurrent; // take this and place it into an array
// condition invalid
if(scoreCurrent>upperLimit || scoreCurrent<0)
{
int current=index-1;
cout<<"Invalid score."<<endl;
index=current;
scoreCurrent=0;
}
scoreTotal+=scoreCurrent;
average=(float) scoreTotal/(float) students;
if(scoreCurrent>average)
{
// scoreCurrent values are placed in belowAve array;
}
if(scoreCurrent>average)
{
// scoreCurrent values are placed in aboveAve array;
}
}
// display
cout<<"Average: "<<average<<endl;
cout<<"Scores above or equal average: "<<belowAve<<endl;
cout<<"\nScores below average: "<<aboveAve<<endl;
return 0;
}
My guess is that scorecurrent is an array (and index the offset in scorecurrent)? If you think that this will work
std::cin >> scoreCurrent;
then the problems are:
where in scorecurrent will the input be placed (you don't use index)?
(if you want to give scores for all indices) when does the input stop?
Apart from the argument that a vector is better (which it is, because you don't need to specify its size and can just push_back()) I think this solution is a very elegant way to solve your problem.
It uses a lambda function to iterate over all elements of a (fixed-sized) array. There is also another, more traditional solution where the >> operator of std::cin is overloaded for arguments of array types.
I'm attempting a logical comparison at an element in a char-array based on index number but my compiler says illegal comparison. Any ideas about what's going on?
#include <iostream>
#include <cstring>
#include <iomanip>
#include <fstream>
using namespace std;
ofstream MyFile("Assignmentfile.txt");
int userno;
char name[16];
char lastname[16];
char address[51];
char cellno[14];
char landlineno[12];
int sent;
void userinput();
void searchfunc();
void deletecontact();
void displaycontact();
void modifycontact();
void sortcontact();
void findcontact();
int main()
{
MyFile<<"First Name Last Name Address Cell Number Landline Number"<<endl;
userinput();
return 0;
}
void userinput()
{
{
cout<<"Would you like to enter a new contact? (1/0) ";
cin>>sent;
while (sent==1)
{
cout<<"Enter Name: ";
cin>>name;
MyFile<<left<<setw(16)<<name<<"|";
cout<<"Enter Last name: ";
cin>>lastname;
MyFile<<left<<setw(16)<<lastname<<"|";
cout<<"Enter Address: ";
cin>>address;
MyFile<<left<<setw(51)<<address<<"|";
cout<<"Enter Cell Number: ";
cin>>cellno;
if (cellno[0]=="+")
{
cout<<"Enter Cell number again starting with +92"; // The problem appears here //
}
MyFile<<left<<setw(14)<<cellno<<"|";
cout<<"Enter Landline Number: ";
cin>>landlineno;
MyFile<<left<<setw(12)<<landlineno<<endl;
cout<<endl;
cout<<"Would you like to enter a new contact? (1/0) ";
cin>>sent;
}
MyFile.close();
}
}
The program must be able to write and read from a text file. It can create contacts, modify them, delete them, sort them and search through them. The problem is that the cell number must start from "+92" i.e "+923454356568". I thought that if (cellno[0]=="+") and so on would work.
I cannot use strings and only have to rely on character type arrays. Using strings would make all of this a piece of cake.
Below is the assignment I wish to complete.
Your problem is this line:
if (cellno[0]=="+")
You are comparing single character, at index 0 in cellno char array (which hopefully contains a C string) with string literal, which is a pointer (as your compler error says).
You want to compare a single char, like this:
if (cellno[0]=='+')
Note how single and double quotes have a very different meaning!
You code has a lot of other issues, too many to list here, but that should solve the problem you are asking about. But one advice I add: do not use C strings in C++, if you can avoid it! Use std::string as soon as you are allowed to!
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 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.
I am trying to solve a problem which is like, if you enter a name: Eve which have three letters, so the program will eliminate the suitor of the multiple of that letter. If the multiple exceeds the size of the vector, then it will return back from the first index and so on. Did a cin for string because I just need the first name.
The program exits after the input. Tried to comment the last for loop and it worked fine, but that's the main part. Appreciate help, thanks in advance.
#include<iostream>
#include<vector>
#include<stdlib.h>
using namespace std;
int main()
{
int nos,n; string name;
cout<<"Enter Number of Suitors: "<<endl;
cin>>nos;
cout<<"Enter Your First Name: "<<endl;
cin>>name;
n=name.size();
vector<int>suit(nos);
for(int i=0;i<nos;i++)
suit[i] = i+1;
for(int i=0;i<nos;i++)
cout<<suit[i]<<" ";
for(n=n-1;(suit.size()!=1);n+=n)
{
n = n%nos;
suit.erase(suit.begin(),suit.begin()+n);
}
cout<<suit.front();
system("pause");
return 0;
}//close main