2016-09-23 73 views
0

我有一个txt文件,里面有很多东西。 线条有这样的模式:6个空格然后是1个int,1个空格,然后是一个字符串。 此外,第一行有txt所具有的行数。Txt到2个不同的数组C++

我想将整数整数ints和字符串数组中的字符串。

我可以读取它并将其放入一个数组中,但前提是我将int整理为字符并将其放入一个字符串数组中。当我尝试分离事物时,我不知道该怎么做它。有任何想法吗?

我用于把一切都放到一个阵列中的代码是这样的:

int size() 
{ 
    ifstream sizeX; 
    int x; 
    sizeX.open("cities.txt"); 
    sizeX>>x; 

    return x; 
}; 


int main(void) 
{ 
    int size = size(); 
    string words[size]; 

    ifstream file("cities.txt"); 
    file.ignore(100000,'\n'); 

    if(file.is_open()) 
    { 
     for(int i=0; i<size; i++) 
     { 
      getline(file,words[i]); 
     } 
    } 
} 
+1

你能告诉你的文件布局的实际例子吗? – NathanOliver

回答

0

刚开始我将提供有关您的代码的一些提示:

  • int size = size(); 为什么你需要打开文件,阅读第一行然后关闭它?该过程可以完成一次打开文件。代码​​绝对不合法C++。您不能在C++中实例化variable-length-arrayC功能已被列入C++标准(some ref)。我建议你用std::vector来代替,这是更多的C++代码。


这里我写的函数的代码段,其执行你所需要的。

int parse_file(const std::string& filename, 
       std::vector<std::string>* out_strings, 
       std::vector<int>* out_integers) { 
    assert(out_strings != nullptr); 
    assert(out_integers != nullptr); 

    std::ifstream file; 
    file.open(filename, std::ios_base::in); 
    if (file.fail()) { 
    // handle the error 
    return -1; 
    } 

    // Local variables 
    int num_rows; 
    std::string line; 

    // parse the first line 
    std::getline(file, line); 
    if (line.size() == 0) { 
    // file empty, handle the error 
    return -1; 
    } 
    num_rows = std::stoi(line); 

    // reserve memory 
    out_strings->clear(); 
    out_strings->reserve(num_rows); 
    out_integers->clear(); 
    out_integers->reserve(num_rows); 

    for (int row = 0; row < num_rows; ++row) { 
    // read the line 
    std::getline(file, line); 
    if (line.size() == 0) { 
     // unexpected end of line, handle it 
     return -1; 
    } 

    // get the integer 
    out_integers->push_back(
     std::stoi(line.substr(6, line.find(' ', 6) - 6))); 

    // get the string 
    out_strings->push_back(
     line.substr(line.find(' ', 6) + 1, std::string::npos)); 
    } 
    file.close(); 

    return 0; 
} 

你绝对可以改善它,但我认为这是一个很好的起点。

最后的建议我可以给你,为了提高你的代码的健壮性,你可以匹配每行regular expression。通过这种方式,您可以确保您的线路的格式完全符合您的需求。

例如:

std::regex line_pattern("\\s{6}[0-9]+\\s[^\\n]+"); 
if (std::regex_match(line, line_pattern) == false) { 
    // ups... the line is not formatted how you need 
    // this is an error 
}