2013-05-15 56 views
1

我正在使用C++中的文件名。我需要知道如何提取文件名的某些部分? 文件的名稱是這樣的:從文件名中提取數字

/home/xyz/123b45.dat 

/home/xyz/012b06c.dat 

/home/xyz/103b12d.dat 

/home/xyz/066b50.dat 

欲之後從陣列中的每個文件名和存儲「B」(45,06,12,50)中提取兩個數字。任何人都可以請建議如何去做...

+1

你想從文件名中提取兩個數字,還是要以可視化向量的載體? – juanchopanza

+0

矢量矢量是一個古老的問題!這個問題是關於文件名.... @ juanchopanza – learner

+0

對不起!忘了標題! @ juanchopanza – learner

回答

4

使用std::string::findstd::string::substr

int main() 
{ 
    std::string line; 
    std::vector<std::string> parts; 
    while (std::getline(std::cin, line)) 
    { 
     auto suffix = line.find(".dat"); 
     if (suffix != std::string::npos && suffix >= 2) 
     { 
      std::string part = line.substr(suffix-2, 2); 
      parts.push_back(part); 
     } 
    } 

    for (auto & s : parts) 
     std::cout << s << '\n'; 

    return 0; 
} 

輸出繼電器您的輸入:

$ ./a.out < inp 
45 
06 
12 
50 

或者,如果你是絕對相信每一行良好的,你可以更換的內迴路如下:

std::string part = line.substr(line.size()-6, 2); 
parts.push_back(part); 

(不推薦)。

編輯:我注意到你改變問題的標準,所以這裏的新標準置換循環:

auto bpos = line.find_last_of('b'); 
if (bpos != std::string::npos && line.size() >= bpos+2) 
{ 
    std::string part = line.substr(bpos+1, 2); 
    parts.push_back(part); 
} 

注意所有這些變化都具有相同的輸出。

你也可以在裏面夾一個isdigit,這也是很好的選擇。

最後編輯:這是完整版本bposc++98兼容:

#include <iostream> 
#include <vector> 
#include <string> 

int main() 
{ 
    std::string line; 
    std::vector<std::string> parts; 
    // Read all available lines. 
    while (std::getline(std::cin, line)) 
    { 
     // Find the last 'b' in the line. 
     std::string::size_type bpos = line.find_last_of('b'); 
     // Make sure the line is reasonable 
     // (has a 'b' and at least 2 characters after) 
     if (bpos != std::string::npos && line.size() >= bpos+2) 
     { 
      // Get the 2 characters after the 'b', as a std::string. 
      std::string part = line.substr(bpos+1, 2); 
      // Push that onto the vector. 
      parts.push_back(part); 
     } 
    } 

    // This just prints out the vector for the example, 
    // you can safely ignore it. 
    std::vector<std::string>::const_iterator it = parts.begin(); 
    for (; it != parts.end(); ++it) 
     std::cout << *it << '\n'; 

    return 0; 
} 
+0

嘿@BoBTFish!非常感謝!! 你能幫我解決我收到的錯誤......它說:「錯誤:'bpos'沒有命名一個類型」 我該怎麼辦? 謝謝!!! – learner

+0

你不是用'C++ 11'支持編譯的。如果這不是一個選項,'bpos'的類型是'std :: string :: size_type'(這就是爲什麼我使用'auto',這很容易忘記或懶惰,並使用錯誤的類型)。 – BoBTFish

+0

我在C++ 98模式下。它說: 「錯誤:基於範圍的for循環不允許在C++ 98模式」 我不明白這一點.....我沒有太多先進的C++ ...謝謝你的幫助...請建議如何實現循環,然後... – learner

0

考慮到你的問題的標題,我假設你存儲的文件名爲vectorschars。更好的方法是使用std::string s。字符串允許各種設施功能,包括標記和檢索子串等等(這是你想要做的)。

+0

對不起!!!忘了編輯標題!它沒有載體... @Marc Claesen – learner