2010-04-19 41 views
2

我有一個格式爲1,3-7,10,11-15, 的字符串輸入我想確定所有在該範圍內輸入的整數。我如何使用C++實現這一點?如何使用C++將一系列整數轉換爲列表

TIA 顧比

+0

這是功課? – 2010-04-19 14:22:49

+4

你到目前爲止嘗試過什麼?這是什麼讓你困惑?這是作業嗎?如果您提供更多信息,您會得到更多/更好的答案。 – rmeador 2010-04-19 14:23:19

回答

4

此問題屬於解析的域。你會使用一個解析器。解析器解釋一種語言。在你的情況下,語言會看起來像這樣的事情:

input = comma-separated sequence of fragments 
fragment = integer or range 
range = integer-integer 
integer = sequence of digits 0..9 
1
//Disclaimer -- untested 
//Disclaimer -- this is not good code, but it's a quick and dirty way to do this 
//    if you're trying to see a possible solution. 

#include <algorithm> 
#include <functional> 
#include <vector> 

const char input[] = "1,3-7,10,11-15"; 
const char * inputBegin = input; 
const char * inputEnd = input + strlen(input); 
std::vector<int> result; 
for(; inputBegin < inputEnd; inputBegin = std::find_if(inputBegin, inputEnd, isdigit)) { 
    int first = *inputBegin - '0'; 
    for(inputBegin++; inputBegin < inputEnd && isdigit(*inputBegin); inputBegin++) 
     first = first * 10 + (*inputBegin - '0'); 
    int last = first; 
    if (++inputBegin < inputEnd && *inputBegin == '-') { 
     last = inputBegin - '0'; 
     for(inputBegin++; inputBegin < inputEnd && isdigit(*inputBegin); inputBegin++) 
      last = last * 10 + (*inputBegin - '0'); 
    } 
    for(; first < last; first++) 
     result.push_back(first); 
} 
+0

對於任何公開承認它在工作的人來說,這不是最好的解決方案。希望更多人在他們的博客上這樣做。 – wheaties 2010-04-19 15:26:23

+0

這段代碼很可怕。徹頭徹尾的噁心,真的。但我不會因爲小麥提到的相同原因而使你失望。 – rmeador 2010-04-19 15:32:35

+0

由於缺乏空白和平靜的綠色評論,它看起來更可怕。 – 2010-04-20 08:00:44

相關問題