c++ “>>”符号的影响

11 篇文章 0 订阅
今天在群中见到一位仁兄问一个C++问题,当时没想太多,直接接了下来,如下:
#include <iostream.h>
#include <string>

class student
{
public:
student(char name1[]="",int sco=0)
{
strcpy(name,name1);
score=sco;
}
void print()
{  cout<<name<<'\t'<<score<<endl;  }
public:
char name[20];
int score;
};
void main()
{
int max,i;
student s[5]={student("chen",86),student("shu",89),student("song",76),student("zhu",87),student("zong",90)};
for(i=0;i<5;i++)
s[i].print();
max=s[0].score;
for(i=0;i<5;i++)
{
if(s[i].score>max)
{
max=s[i].score;
a=s[i].name;
}
}
cout<<"the highest score is:"<<max<<endl;
}  

以上是原始材料,那位仁兄想为最高分输出名字,但苦于错误,所以便来群众求助,在帮助他解决问题的时候,自己也遇到一些问题,如下:
一:直接编译,导致“fatal error C1010: unexpected end of file while looking for precompiled header directive”错误。
这个奇葩问题不是一次两次了,相信诸位也经常遇到吧,其实解决办法很简单,只需要在代码首添加“#include "stdafx.h"”即可解决。
二: cout无法输出string类型。 
 这个问题也不是问题,只是咱书看少了,其实只要写成string.c_str(),即可,因为“>>”只支持基本类型,string自然无法识别,使用c_str()会自动返回const char*输出,自然问题迎刃而解,下面便是修改了的代码。
 
#include "stdafx.h"
#include <iostream.h>
#include <string>
using namespace std;

class student
{
public:
student(char name1[]="",int sco=0)
{
strcpy(name,name1);
score=sco;
}
void print()
{  cout<<name<<'\t'<<score<<endl;  }
public:
char name[20];
int score;
};
int main()
{
int max,i;
student s[5]={student("chen",86),student("shu",89),student("song",76),student("zhu",87),student("zong",90)};
for(i=0;i<5;i++)
s[i].print();
max=s[0].score;
string a=s[0].name;
for(i=0;i<5;i++)
{
if(s[i].score>max)
{
max=s[i].score;
a=s[i].name;
}
}
cout<<"the highest score is:"<<max<<a.c_str()<<endl;
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值