首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

求指针的有关问题,为何结果不对!

2012-04-27 
求高手指点指针的问题,为何结果不对!!!!#includeiostream#includefstream#includestringusingnamesp

求高手指点指针的问题,为何结果不对!!!!
#include   <iostream>
#include   <fstream>
#include   <string>
using   namespace   std;

int   main(){
string     name;
int   age;
string     address;
float   score;


fstream   ifs( "student.txt ");
                if(!ifs){
                                cout < < "open   file   error! " < <endl;
                }
                char   *   buf[4];
                char   s[100];
                int   i=0;
                while(!ifs.eof()){
                                                                                                                                                               
                                memset(s,0,sizeof(100));
                                //if(ifs.eof()){break;}
                                ifs.ignore(255, '= ');
                                ifs.getline(s,sizeof(s));
                                buf[i]=s;
                                i++;
                }
                                                                                                                                                               
                ifs.close();
name=buf[0];
age=atoi(buf[1]);
address=buf[2];
score=atoi(buf[3]);

cout < < "name: " < <name < <endl;
cout < < "age: " < <age < <endl;
cout < < "address: " < <address < <endl;
cout < < "score: " < <score < <endl;
return   0;
                                                                                                                           


}
其中,txt的内容如下

Name=wayz
Age=32
Address=Hai   Dian   district,Beijing
Score=90

该程序要求将文本文件中的姓名,年龄,地址,成绩赋值到相应的变量里再输出到屏幕.
但我运行时发现最后姓名,年龄,地址,成绩都变成了90,请知道的高手指点一下,谢谢:)

[解决办法]
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
string name;
int age;
string address;
float score;


fstream ifs( "student.txt ");
if(!ifs){
cout < < "open file error! " < <endl;
}
char * buf[4];
char s[100];
int i=0;
while(!ifs.eof()){

memset(s,0,sizeof(s));//我把这里改为初始化s数组为全0,不知道楼主原代码是什么目的
//if(ifs.eof()){break;}
ifs.ignore(255, '= ');
ifs.getline(s,sizeof(s));
char* temp=new char[100];//因为楼主的buf数组里的4个数组指针都指向同一空间,所以最后结果都是90
memcpy(temp,s,sizeof(s));//应该读取一项数据后再为这份数据创建空间
buf[i]=temp;//buf指针指向新的空间
i++;
}

ifs.close();
name=buf[0];
age=atoi(buf[1]);
address=buf[2];
score=atoi(buf[3]);

cout < < "name: " < <name < <endl;
cout < < "age: " < <age < <endl;
cout < < "address: " < <address < <endl;
cout < < "score: " < <score < <endl;
return 0;

}

热点排行