2015-05-14 66 views
-1

我試圖從管道分隔文件中獲取第2和第5列的詳細信息。從管道分隔文件中獲取值

第5列在從虛擬文件中讀取時正在修剪。我也嘗試使用get line功能。如何獲得字符串中的整個第5列?

文件看起來像:

1|6705|SW|447|C/A-"WAR" FROM CAR COMPANY |||RFD|E|0| 
2|6706|CA|448|CAR TYPE OR CUST. ID, REQ  |||RFD|E|0| 
3|6707|CZ|448|CAR TYPE OR CUST. ID, REQ  |||RFD|E|0| 

代碼

std::string cmd = "awk -F'|' '{ print $2, $5 }' 1.txt >> tmp.txt"; 
    system(cmd.c_str());// extract the two columns and write to dummy file 
    ifstream read("tmp.txt"); 
    std::string line; 

    while (std::getline(read, line)) // Read the file line by line 
    { 
      std::istringstream iss(line); 
      string a, b; 
      if (!(iss >> a >> b)) { break; } // error 
      std::cout<<"a"<<a<<" b "<<b<<std::endl; 
    } 
    read.close(); 
    system("rm tmp.txt"); 

輸出

鍵(字符串):6705,值(INT):C/A-「WAR 「
key(string):6706,value(int):CAR
key(string):6707,value(int) :CAR

回答

1

的給std :: cin >>操作讀取由空格或換行符的字符串,所以在你的情況下,C/A-"WAR" FROM CAR COMPANY值將被截斷成C/A-"WAR"FROMCARCOMPANY。 您可以改用getline

while (std::getline(read, line)) // Read the file line by line 
{ 
     std::istringstream iss(line); 
     string a, b; 
     iss>>a; 
     getline(iss,b);//This may work 
     std::cout<<"a"<<a<<" b "<<b<<std::endl; 
}