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!
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 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.
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 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");