2017-10-11 2 views
0

このlog.txtテキストファイルを私のプログラムの構造体に読み込む方法は? +++ /////////このログテキストファイルをC++で読むには

Port4000.txt:M:r:10 

Port4001.txt:M:w:1 

Port4002.txt:M:w:9 

Port4003.txt:J:x:1 

表します

Port40xx.txtポート番号 を表す: Mは、ユーザ 表す: Rを作用 を表す: 10が閾値を表します

///////////////// ///////////////////////////////

struct Pair 
{ 

char user; 

char action; 

} 

int main() 
{ 

    Pair pairs; 

    ifstream infile; 

    char portnumber[20]; 


    infile.open("logs.txt",ios::in); // `open the log text file ` 


    infile.getline(portnumber,20,':'); //`Reading the portnumber of the user and action 
` 

infile >> pairs.user >> pairs.action >> threshold; 

//`THE PROBLEM IS HOW TO read the user, action, threshold whenever it meets ":" symbol?` 

infile.close(); 

return 0; 

} 

charデータ型を ":"シンボルに一致するまで読み込み、別のcharデータ型を読み始める方法があるかどうかを教えてください。ありがとう:)

+0

「Port40xx.txtはポート番号を表します」 - これは奇妙な数字です – sehe

答えて

1

あなたはちょうどあなたが "ポート番号" のために何をしたかやり続けることができます。std::getlineの使用は、より安全な(そしてより便利)です

Live On Coliru

#include <fstream> 
#include <iostream> 

struct Pair { 
    char user; 
    char action; 
}; 

int main() 
{ 

    std::ifstream infile; 

    infile.open("logs.txt", std::ios::in); // `open the log text file ` 

    std::string portnumber, user, action, threshold; 
    if (getline(infile, portnumber, ':') 
      && getline(infile, user, ':') && user.size() == 1 
      && getline(infile, action, ':') && action.size() == 1 
      && getline(infile, threshold, '\n')) 
    { 
     Pair pair { user[0], action[0] }; 

    } 
} 

ノートよりstd::istream::getline