2016-10-13 29 views
0

我在C++中實現了一個像Python一樣的split()函數來訓練我自己。我從這個SO線程的想法:Parse (split) a string in C++ using string delimiter (standard C++)一段時間內聲明中的奇怪行爲C++

在此代碼:

while ((pos = s.find(delimiter)) != std::string::npos) { 
    token = s.substr(0, pos); 
    std::cout << token << std::endl; 
    s.erase(0, pos + delimiter.length()); 
} 

OS poswhile循環的條件內指定的值。

我想同樣的事情:

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

std::vector<std::string> split(std::string inp, std::string delimeter){ 
    std::vector<std::string> res; 
    while (size_t pos = inp.find(delimeter) <= inp.length()){ 
     std::cout << inp << " " << pos << std::endl ; 
     if (inp.substr(0, delimeter.length()) == delimeter) { 
      inp.erase(0, delimeter.length()); 
      continue; 
     } 
     res.push_back(inp.substr(0, pos)); 
     inp.erase(0, pos); 
    } 
    return res; 
} 

int main() { 
    for (auto i : split(",,ab,c,,d", ",")){ 
     std::cout << i << " "; 
    } 
    std::cout << std::endl; 
} 

我的輸出是:

,,ab,c,,d 1 
,ab,c,,d 1 
ab,c,,d 1 
b,c,,d 1 
,c,,d 1 
c,,d 1 
,,d 1 
,d 1 
a b c 

我的問題是,爲什麼它POES說的,字符串,,ab,c,,d 1位置是1

爲什麼ab,c,,d中的位置也是1?

我修改這樣的代碼:

#include <iostream> 
... 
    size_t pos = 0; 
    while (pos <= inp.length()){ 
     pos = inp.find(delimeter); 
     ... 
} 

int main() { 
    for (auto i : split(",,ab,c,,d", ",")){ 
     std::cout << i << " "; 
    } 
    std::cout << std::endl; 
} 

...保持不變,現在,它的工作原理就像一個魅力,輸出是:

,,ab,c,,d 0 
,ab,c,,d 0 
ab,c,,d 2 
,c,,d 0 
c,,d 1 
,,d 0 
,d 0 
d 18446744073709551615 
ab c d 

正如我所料。

所以我的問題是:爲什麼不能在一個while條件中聲明一個變量?是不是在所有的週期評估條件(因此聲明再次發生?)即使在第一個週期我得到結果1這是錯誤的。這是爲什麼?當你需要一個完全不同的分組

while ((size_t pos = inp.find(delimeter)) <= inp.length()){ 

後者是用C++非法雖然

+4

您對第一個代碼示例的陳述是錯誤的。這讓問題變得混亂!已在循環之前聲明瞭「pos」。 – juanchopanza

+0

在第一個代碼中,「pos」沒有在for循環中聲明。它應該在某個地方被宣佈。 – NathanOliver

+0

「爲什麼不能在一段時間內聲明一個變量?」您可以。只要記住變量的作用域在循環的每次迭代時都會被重置 – UKMonkey

回答

5
while (size_t pos = inp.find(delimeter) <= inp.length()){ 

被解釋爲

while (size_t pos = (inp.find(delimeter) <= inp.length())){ 

不可能在while條件中聲明變量,同時使其參與更復雜的條件表達式(如與另一個值進行比較)。當你在C++中聲明一個變量的時候,你所能擁有的就是它的初始值轉換爲bool。

修改的代碼,其中pos在循環之前聲明,正確實現您的意圖。

+0

所以我正在檢查一個條件,並得到了一個boolean 1.這解釋了它,它的如此清晰..我只是坐在這裏的時間和喜歡找到它。非常感謝,我會盡快標記這是正確的盡我所能(10分鐘) –