今天在群中见到一位仁兄问一个C++问题,当时没想太多,直接接了下来,如下:
以上是原始材料,那位仁兄想为最高分输出名字,但苦于错误,所以便来群众求助,在帮助他解决问题的时候,自己也遇到一些问题,如下:
一:直接编译,导致“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>
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;
}