2012-08-06 60 views
0

我是C++新手。我想知道如何創建一個函數來檢查分隔符。C++如何檢查此文本文件中的分隔符

如下面

AD,Andorra,AN,AD,AND,20.00,Andorra la Vella,Europe,Euro,EUR,67627.00 
AE,United Arab Emirates,AE,AE,ARE,784.00,Abu Dhabi,Middle East,UAE Dirham,AED,2407460.00 
AF,Afghanistan,AF,AF,AFG,4.00,Kabul,Asia,Afghani,AFA,26813057.00 

的情況下,如果分隔成爲$或#而不是逗號,我如何創建一個函數來檢查它說,文本文件的格式不正確。

謝謝!

下面是我READDATA代碼

void readData() 
{ 
    FILE * pFile; 
    NoOfRecordsRead = 0; 
    char buffer [Line_Char_Buffer_Size]; 

    pFile = fopen (INPUT_FILE_NAME , "r"); 

    if (pFile == NULL) 
     perror ("Error opening file 'Countries.txt' !"); 
    else 
    { 
     while (!feof (pFile)) 
     { 
      char* aLine = get_line (buffer, Line_Char_Buffer_Size, pFile); 

      if (aLine != NULL) 
      { 
//    printf ("%d] aLine => %s\n", NoOfRecordsRead, aLine); 
       globalCountryDataArray [NoOfRecordsRead++] = createCountryRecord (aLine); 
      } 
     } 

    fclose (pFile); 

    } 
} 
+1

發佈您的代碼,對於逗號的作品。 – 2012-08-06 09:59:43

+0

發佈你現在的工作代碼片段,以便我們可以幫助你更好。 – askmish 2012-08-06 10:01:58

+1

'如果分隔符變成$或#而不是逗號,我如何創建一個函數來檢查它並說錯誤格式的文本文件「 - 這個**必然假定**既不是$也不是** * *部分數據,否則無法告訴您使用$或#是否有意爲之 – YePhIcK 2012-08-06 10:02:46

回答

0
#include <string> 
#include <fstream> 
#include <algorithm> 

bool detect_comma(std::string file_name) 
{ 
    // open C++ stream to file 
    std::ifstream file(file_name.c_str()); 
    // file not opened, return false 
    if(!file.is_open()) return false; 
    // read a line from the file  
    std::string wtf; 
    std::istream &in= std::getline(file, wtf); 
    // unable to read the line, return false 
    if(!in) return false; 
    // try to find a comma, return true if comma is found within the string 
    return std::find(wtf.begin(), wtf.end(), ',')!= wtf.end(); 
} 


#include <iostream> 
#include <cstdlib> 

int main() 
{ 
    if(!detect_comma("yourfile.dat")) 
    { 
     std::cerr<< "File is not comma delimited!\n"; 
     return EXIT_FAILURE; 
    } 
    // file is OK, open it and start reading 
} 

編輯:添加註釋&示例代碼

+0

一些解釋什麼這個代碼的作用和它的工作原理將不勝感激。 – 2012-08-06 11:40:47

+0

添加了評論和示例代碼 – nurettin 2012-08-06 11:50:41

0

您將需要一個可靠的方式來發現你總是希望分隔符是一個位置。如果第一個字段總是2個字符寬,則可以檢查以查看字符是否爲,。否則,您可以在第一行文本上向後掃描以查看第一個與貨幣無關的字符是否爲,

編輯:readData例程是非常C-中心,正如在評論中已經指出。通過使用C++功能,您可以大大簡化它。

std::string aLine; 
std::ifstream pfile(INPUT_FILE_NAME); 
while (pfile) { 
    std::getline(pfile, aLine); 
    if (aLine.size()) { 
     globalCountryDataArray.push_back(createCountryRecord(aLine)); 
    } 
} 
0

執行支票使用Boost.Regex庫的一個好方法。您只需定義正則表達式並執行檢查,如果您的輸入與表達式匹配。

示例代碼:

#include <string> 
#include <boost/regex.hpp> 

using namespace std; 

int main() 
{ 
    const string input("AD,Andorra,AN,AD,AND,20.00,Andorra la Vella,Europe,Euro,EUR,67627.00"); 
    const boost::regex ex("(?:(?!,)(\\d+\\.\\d*)|(\\w|\\s)*)(,(?:(?!,)(\\d+\\.\\d*)|(\\w|\\s)*))*"); 
    cout << boost::regex_match(input.c_str(), ex) << endl; 
    return 0; 
} 

順便說一句:我不是一個正則表達式的專家,所以驗證表達式:-)

相關問題