2014-12-05 2 views
-1
#include<iostream> 
#include<fstream> 
#include<stdlib.h> 
#include<string.h> 
using namespace std; 
class Data 
{ 
public: 
    char name[20]; 
    long long int ph; 
    Data() 
    { 
     strcpy(name," "); 
     for(int i=0;i<10;i++) 
     ph=0; 
     } 
    void getdata() 
    { 
     cin>>name; 
     cin>>ph; 
     } 
}; 

int main() 
{ 
int n; 
fstream file; 
file.open("test1.txt",ios::app|ios::out); 
if(!file) 
{ 
    cout<<"file open error"<<endl; 
    return 0;} 
cout<<"number of data you want to enter"<<endl; 
cin>>n; 
char a[1000]; 
//Data temp; 
Data d[n]; 
for(int i=0;i<n;i++) 
{ 
    d[i].getdata(); 
    file<<d[i].name<<" "; 
    file<<d[i].ph<<endl; 
    } 
    file.close(); 
file.open("test1.txt",ios::in); 
file.seekg(0); 
file>>a; 
while(!file.eof()) 
{ 
    cout<<a<<endl; 
    file>>a; 
    //cout<<a<<endl; 
    } 
cout<<"Enter the index"<<endl; 
int in; 
cin>>in; 
int pos=(in-1)*(sizeof(d[0])); 
file.seekg(pos);  
    file>>a; 
    //cout<<a<<endl; 
    file.read((char *)(&d[pos]),sizeof(d[0])); 
    cout<<a<<endl; 
    file.close(); 
    system("pause"); 
    return 0; 
} 

에서 읽는 동안 특정 출력을 얻을 방법 : 입력 할 데이터의

2
ABC (88)
XYZ 99
인덱스를 입력 :
를 xyz 99 //이 출력을 얻어야합니다.
99 //이 출력을 얻고 있습니다
이 코드는 해당 파일에있는 문자 배열을 읽지 않습니다.나는 다음과 같은 데이터를 입력하고 경우 파일

+0

이 태그를 C++로 태그 했으므로 C 스타일 문자열을'std :: string'으로 대체하십시오. –

답변

0

너무 복잡하여 더 간단한 해결책을 제시합니다.

class Data 
{ 
    public: 
    Data (const std::string& new_name = "", 
      long long int new_ph = 0LL) 
    : name(new_name), ph(new_ph) // Initialization list 
    { ; } 

    friend std::istream& operator>>(std::istream& inp, 
            Data& d); 
    friend std::ostream& operator<<(std::ostream& out, 
            const Data& d); 
    private: 
    std::string name; 
    long long int ph; // I recommend a string for phone numbers 
}; 

std::istream& operator>>(std::istream& inp, 
         Data& d) 
{ 
    inp >> d.name; 
    inp >> d.ph; 
    return inp; 
} 

std::ostream& operator>>(std::ostream& out, 
         const Data& d) 
{ 
    out << d.name << ' ' << d.ph << "\n"; 
    return out; 
} 

// ... 
std::vector<Data> my_vector; 
input_file >> quantity; 
input_file.ignore(10000, '\n'); 
Data d; 
while (input_file >> d) 
{ 
    my_vector.push_back(d); 
} 
for (unsigned int i = 0; i < my_vector.size(); ++i) 
{ 
    cout << my_vector[i]; 
} 
//... 

나는 Data 항목에서 읽을 수있는 operator>> 과부하 및 출력 operator<<Data 항목을 오버했다.

이름을보고 char[]을 사용하지 마십시오. 메모리 할당이나 이름 오버플로에 대해 걱정할 필요가 없습니다.

입력 내용을 파일 및 콘솔 입력과 함께 변경하지 않고 사용할 수 있습니다!