苏联二战轻武器:c++问题求解

来源:百度文库 编辑:神马品牌网 时间:2024/04/29 06:47:27
#include <iostream.h>
# define N 2
struct node
{int num;
char name [N];
char male[N];
int tel;
node *next;};

void main(){
node *p;
node *head='\0';
int i;
for (i=0;i<N;i++)
{p=new(node);
cout<<"input"<<i<<"information";
cin>>(*p).num>>(*p).name>>(*p).male>>(*p).tel;
(*p).next=head;
head=p;}
char x[N];
cout<<"input name:";
cin>>x[N];

while (p!='\0')
{if((*p).name==x)
{cout<<(*p).num<<" "<<(*p).name<<" "<<(*p).male<<" "<<(*p).tel;break;}
else p=(*p).next;}if (p=='\0') cout<<"not found";
}
错在哪?谢谢!

这样就行了:有注释:

#include <iostream.h>
#include "string.h"
#define N 10 // 字符数组的长度 name[N], male[N]
#define M 3 // 信息总条数

struct node
{
int num;
char name [N];
char male[N];
int tel;
node *next;
};

void main(){
node *head=NULL; //写成NULL 更好
int i;
for (i=0;i<M;i++)
{
node *p=new node;
cout<<"input "<<i<<" information:"<<endl;
cin>>(*p).num>>(*p).name>>(*p).male>>(*p).tel;
(*p).next=head;
head=p;
}
char x[N];
cout<<"input name:";
cin>>x; // 不能是 x[N]
node *p = head;
while (p!=NULL)
{
if(strcmp(p->name,x)==0) // 不能是 (*p).name==x
{
cout<<(*p).num<<" "<<(*p).name<<" "<<(*p).male<<" "<<(*p).tel<<endl;
break;
}
else p=(*p).next;
}
if (p==NULL) cout<<"not found";
}

问题多多啊,试一试这个 ^_^

#include <iostream>

using namespace std;

#define LEN 8
#define N 2

struct node
{
int num;
string name;
string male;
int tel;
node *next;
};

int main(int argc, char *argv[])
{
node *p;
node *head='\0';
int i;
for (i=0; i<N; i++)
{
p = new(struct node);
cout << "input" << i << "information : ";
cin >> (*p).num >> (*p).name >> (*p).male >> (*p).tel;
(*p).next = head;
//cout << "OK : " << (*p).num << " " << (*p).name << " " << (*p).male << " " << (*p).tel << endl;
head = p;
}

string name;
cout << "input name : ";
cin >> name;
//cout << "input name is : " << name.c_str() << endl;

while (p!='\0')
{
if( p->name==name )
{
cout << "OK : " << p->num << " " << p->name << " " << p->male << " " << p->tel << endl;
break;
}
else
p = p->next;
}
if (p=='\0')
cout<<"not found" << endl;

return 0;
}

cin>>x[N];

找到没有?应该写为cin>>x;
cin>>x[N];的意思是输入并存储到x[N],(在这里也就是x[2])显然,这不是我们要的结果.

第一:我记得以往写C语言程序时,空指针都用NULL,'/0'好像很少这么用……
第二:这是一个顺序输入单向链表,然后再根据输入的姓名字符串查询列出某一节结点的值。但是因为由于结构体node中字符数组name与male的长度是由常数N决定的,而本程序N=2,那么字符串长度就为3,所以在执行cin>>(*p).num>>(*p).name>>(*p).male>>(*p).tel;
过程中如果输入的字符过多就会导致缓冲区溢出问题。