0

I have A problem in my C++ Code , I want to add 'n' number of Students with there Each Date , but I have an error when I Compare with if , here is my code

#include <iostream>
#include <stdio.h>
#include <string.h>
struct Address
{
char city[20];
char street[20];    
};
struct University
{
char name1[20],name2[20],name3[20]; 
};
struct student 
{   
char name[20];
char degree[20];
University un;
Address add;
};

using namespace std;
int main (){

    student st[20];
    int n,i,j;
    do{cin>>n;}while(n<=0 || n>20);

    for(i=0;i<n;i++)
    {
        cout<<" Name Of student  "<<i+1<<"\n";
        cin>>st[i].name;

        cout<<" Degree Of student  "<<i+1<<"\n";
        cin>>st[i].degree;

        cout<<"   University 1 \n";
        cin>>st[i].un.name1;
        cout<<"   University 2 \n";
        cin>>st[i].un.name2;
        cout<<"   University 3 \n";
        cin>>st[i].un.name3;

        cout<<" Enter The City Of student  "<<i+1<<"\n";
        cin>>st[i].add.city;

        cout<<" Enter The Street Of student  "<<i+1<<"\n";
        cin>>st[i].add.street;

        cout<<"\n* * * * * * * * * * * * * * * * * * * *\n";

    }   

    for(i=0;i<n;i++)
        if(st[i].degree == "phD")
        cout<<st[i].name<<"  is  OK";

    cout<<endl;
    return 0;
}

So , I want To Check if the Student Has "phD" Then Output his name , But I get An Error , there is not output after the Date inputed , Why ? And When I change the date type of "degree" to string then I get Another Error in the if Say (is not a member of 'student').But I Really Want to do it With char , Can Help me please ?

2 Answers 2

1

For members like char city[20];, you should instead consider the std::string type. It provides the equality operator that you use in your comparison (==) and several other features.

Sign up to request clarification or add additional context in comments.

Comments

0

use strcmp (http://en.cppreference.com/w/c/string/byte/strcmp) to compare char strings

like:

for(i=0;i<n;i++)
        if(strcmp(st[i].degree,"phD") == 0)
        cout<<st[i].name<<"  is  OK";

or

IF you wanna use string in struct you can change your code like this :

struct student 
{   
char name[20];
string degree;
University un;
Address add;
};

then your for loop will remain same

5 Comments

thanks , but should I use A Function?Imean Not Done Without function
0-terminated char strings please.
Unless you have specific reason to reinvent the wheel (aka school): Yes, use standard functions.
@user3457718 this is a standard function in string.h please refer en.cppreference.com/w/c/string/byte/strcmp
@user3457718 if you want to use string in struct I edited my answer above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.