[英]C++ Dealing with 'struct' and Strings
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 我的C ++代码有问题,我想在每个日期的位置添加n个学生,但是当与if比较时出现错误,这是我的代码
#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 ? 当我将“
degree
”的日期类型更改为string
时, if
说(不是“学生”的成员),我会遇到另一个错误。但是我真的很想用char
做这个,请问能帮我吗?
For members like char city[20];
对于像
char city[20];
这样的成员char city[20];
, you should instead consider the std::string
type. ,您应该考虑使用
std::string
类型。 It provides the equality operator that you use in your comparison ( ==
) and several other features. 它提供了在比较(
==
)和其他一些功能中使用的相等运算符。
use strcmp
( http://en.cppreference.com/w/c/string/byte/strcmp ) to compare char
strings 使用
strcmp
( http://en.cppreference.com/w/c/string/byte/strcmp )比较char
字符串
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中使用字符串,则可以像这样更改代码:
struct student
{
char name[20];
string degree;
University un;
Address add;
};
then your for loop will remain same 那么您的for循环将保持不变
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.