在一段时间条件C++中声明中的奇怪行为

Gáb*_*dős 0 c++ while-loop

我正在split()用C++ 实现一个类似python的函数来训练自己.我从这个SO线程中得到了这个想法:使用字符串分隔符(标准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());
}
Run Code Online (Sandbox Code Playgroud)

值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;
}
Run Code Online (Sandbox Code Playgroud)

我的输出是:

,,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
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么poes说它,在字符串中的位置,,ab,c,,d 11

为什么这个位置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;
}
Run Code Online (Sandbox Code Playgroud)

哪里...保持不变,现在它就像一个魅力,输出是:

,,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 
Run Code Online (Sandbox Code Playgroud)

正如我所料.

所以我的问题是:为什么我不能在while条件中声明一个变量?是否在所有循环中评估条件(因此声明再次发生?)即使在第一个循环中,我得到的结果1也是错误的.这是为什么?

AnT*_*AnT 5

while (size_t pos = inp.find(delimeter) <= inp.length()){
Run Code Online (Sandbox Code Playgroud)

被解释为

while (size_t pos = (inp.find(delimeter) <= inp.length())){
Run Code Online (Sandbox Code Playgroud)

而你需要一个完全不同的分组

while ((size_t pos = inp.find(delimeter)) <= inp.length()){
Run Code Online (Sandbox Code Playgroud)

后者在C++中是非法的.

不可能在while条件中声明变量,同时使其参与更复杂的条件表达式(比如与另一个值的比较).当你在C++条件中声明一个变量时,所有你可以拥有的是它的初始值转换为bool.

修改后的代码,在pos循环之前声明,正确实现您的意图.