2011-04-24 3 views
0

다음과 같은 구조를 가지고 있습니다 :구조체 멤버에 대한 파일 입력의 예는 무엇입니까?

struct productInfo 
{ 
    int item; 
    string details; 
    double cost; 
}; 

각 항목, 세부 정보 및 비용을 포함하는 10 가지 제품을 입력하는 파일이 있습니다. inFile.getline을 사용하여 입력하려고했으나 작동하지 않습니다. 아무도 나에게 이것을하는 방법의 예를 줄 수 있습니까? 감사 드리고 싶군요.

570314, SanDisk Sansa 클립 8GB MP3 플레이어 검정색, 55.99

예를 들어주십시오.

편집 죄송합니다. C++을 처음 접했고 제안 사항을 이해하지 못했습니다. 이것이 제가 시도한 것입니다.

void readFile(ifstream & inFile, productInfo products[]) 
{ 
    inFile.ignore(LINE_LEN,'\n'); // The first line is not needed 

    for (int index = 0; index < 10; index++) 
    { 
     inFile.getline(products[index].item,SIZE,DELIMETER); 
     inFile.getline(products[index].details,SIZE,DELIMETER); 
     inFile.getline(products[index].cost,SIZE,DELIMETER); 
    } 
} 
+1

작동하지 않는 기능은 무엇입니까? 파일의 내용을 읽으려고 시도한 코드를 보여주십시오. – Mahesh

+2

@Mahesh 나는 그런 코드가 없다고 확신한다. :) –

+0

방금 ​​시도한 코드를 추가했다. – user722049

답변

0

파일 내용은 무엇입니까? 텍스트 인 경우 파일 입력 스트림에서 리디렉션 연산자를 사용할 수 있습니다.

int i; infile >> i;

바이너리 인 경우 & your_struct로 읽을 수 있습니다.

0

사용자는 이어야합니다. 0) productInfo, pinfo의 새 인스턴스를 만듭니다. 1) 첫 번째 쉼표 (',')에 텍스트 (getline 사용)를 읽고이 문자열을 int로 변환하여 pinfo.item에 넣습니다. 2) 텍스트를 다음 쉼표로 읽고 pinfo.details에 넣습니다. 3) endline에 텍스트를 읽고, 문자열을 double로 변환하고, pinfo.cost에 넣습니다.

그럼 파일 끝까지이 작업을 계속하십시오.

0

여기에 getline을 사용하는 방법입니다. 입력 파일에서 읽은 다음 다시 ","에서 해당 행을 잘라내는 데 한 번 사용합니다. 입력이 파일의 각 라인을 읽을 파일 getline()를 읽어 fstream를 사용하는 또 다른 방법이다

99999,"The Best Knife, Ever!",16.95 
+0

왜 문자열 스트림 객체끼리 끼워 넣어야합니까? –

+1

@Matt - 첫 번째'getline' /'stringstream'은 버그, 입력 형식 오류, & c에 관계없이이'>>'가 입력 한 줄을 정확하게 소모한다는 것을 주장합니다. –

1

경우

ostream& operator>>(istream& is, productInfo& pi) 
{ 
    string line; 
    getline(is, line); // fetch one line of input 

    stringstream sline(line); 
    string item; 

    getline(sline, item, ','); 
    stringstream(item) >> pi.item; // convert string to int 

    getline(sline, item, ','); 
    pi.details = item;    // string: no conversion necessary 

    getline(sline, item); 
    stringstream(item) >> pi.cost; // convert string to double 
    return is; 
} 

// usage: 
// productInfo pi; ifstream inFile ("inputfile.txt"); inFile >> pi; 

N.b :이 프로그램은 유모차이다. 줄 자체의 파싱은 목적을 달성하지 못했습니다. since other posts 이미 완료했습니다.

각 행을 읽고 구문 분석 한 후 productInfo로 벡터를 저장하면 모든 제품이 메모리에서 액세스 될 수 있습니다.

#include <iostream> 
#include <fstream> 
#include <vector> 
#include <iterator> 
#include <string> 

using namespace std; 

struct productInfo 
{ 
    int item; 
    string details; 
    double cost; 
}; 

int main() 
{ 
    vector<productInfo> product_list; 

    ifstream InFile("list.txt"); 
    if (!InFile) 
    { 
     cerr << "Couldn´t open input file" << endl; 
     return -1; 
    } 

    string line; 
    while (getline(InFile, line)) 
    { // from here on, check the post: How to parse complex string with C++ ? 
     // https://stackoverflow.com/questions/2073054/how-to-parse-complex-string-with-c 
     // to know how to break the string using comma ',' as a token 

     cout << line << endl; 

     // productInfo new_product; 
     // new_product.item = 
     // new_product.details = 
     // new_product.cost = 
     // product_list.push_back(new_product); 
    }  


    // Loop the list printing each item 

    // for (int i = 0; i < product_list.size(); i++) 
    //  cout << "Item #" << i << " number:" << product_list[i].item << 
    //        " details:" << product_list[i].details << 
    //        " cost:" << product_list[i].cost << endl; 

} 

편집 : 나는 라인을 구문 분석에서 촬영을하기로 결정하고 아래 코드를 썼다. 일부 C++ 사람들은 일을 처리하는 방법이 strtok() 맘에 들지 않을 수도 있지만 거기에 있습니다.

string line; 
while (getline(InFile, line)) 
{ 
    if (line.empty()) 
     break; 

    //cout << "***** Parsing: " << line << " *****" << endl; 

    productInfo new_product; 
    // My favorite parsing method: strtok() 
    char *tmp = strtok(const_cast<char*>(line.c_str()), ","); 
    stringstream ss_item(tmp); 
    ss_item >> new_product.item; 
    //cout << "item: " << tmp << endl; 
    //cout << "item: " << new_product.item << endl; 

    tmp = strtok(NULL, ","); 
    new_product.details += tmp; 
    //cout << "details: " << tmp << endl; 
    //cout << "details: " << new_product.details << endl; 

    tmp = strtok(NULL, " "); 
    stringstream ss_cost(tmp); 
    ss_cost >> new_product.cost; 
    //cout << "cost: " << tmp << endl; 
    //cout << "cost: " << new_product.cost << endl; 

    product_list.push_back(new_product); 
} 
+0

구문 분석을 처리하기위한 대답이 업데이트되었습니다. – karlphillip

+0

좋은 캐치. 곧 코드를 업데이트하겠습니다. 고마워요 @ 로브 – karlphillip

관련 문제