将字符串作为参数传递给char型数组的正确做法:
void setgolf(golf & g,const char *name,int hc)
{
int size=0;
size=strlen(name)+1;
strcpy_s(g.fullname,size,name);
g.handicap=hc;
}
setgolf(gf1,"sadas",3);
int setgolf(golf &g) //这个函数原型很重要
{
cout<<"Enter the fullname:";
cin.getline(g.fullname,10);
if(g.fullname[0]==NULL)
return 0;
cout<<"Enter the hc:";
while( !(cin>>g.handicap) )
{
cin.clear();
while(cin.get() != '\n') //去掉输入流中其它的字符
continue;
cout<<"Please input a integer for handicap."<<endl;
}
while(cin.get() != '\n') //去掉输入流中其它的字符
continue;
return 1; //输入结束返回1
}
第二题
#include<iostream>
#include<string>
using namespace std;
const int ArSize=10;
void strcount(const string str);
int main()
{
string input;
cout<<"Enter a line"<<endl;
getline(cin,input);
while(cin)
{
strcount(input);
cout<<"Enter next line(empty line to quit):"<<endl;
getline(cin,input);
if(input=="")
break;
}
cout<<"Bye"<<endl;
system("pause");
return 0;
}
void strcount(const string str)
{
static int total=0;
int count=0;
cout<<"\""<<str<<"\"contains";
int size=str.length();
for(int i=0;i<size;i++)
{
if(str[i]==' ')
continue;
else if
(str[i]=='\n')
continue;
else
count++;
}
total+=count;
cout << count << " characters\n";
cout << total << " characters total\n";
}
关于getline(cin,str);这个函数其实和cin.getline(str);效果是相同的,只不过getline(cin,str);的参数是string型的,而cin.getline(str)的参数是char型的。
3#include<iostream>
#include<new>
struct chaff
{
char dross[20];
int slag;
};
char buffer[50];
int main()
{
using namespace std;
chaff *p[2];
p[0]=new chaff;
p[1]=new (buffer)chaff;
strcpy_s(p[0]->dross,strlen("zhao")+1,"zhao");
p[0]->slag=1;
strcpy_s(p[1]->dross,strlen("zhao")+1,"wang");
p[1]->slag=2;
cout<<p[0]<<" "<<p[0]->dross<<" "<<p[0]->slag<<endl;
cout<<p[1]<<" "<<p[1]->dross<<" "<<p[1]->slag<<endl;
delete [] p[0];
system("pause");
return 0;
}
由此可见,其实两种方法赋值是一样的。只不过正常分配内存在结束后要设防内存。