有人可以解释/确认下面几行的意思吗?
bool instring{false};
- 这意味着 false 是这个变量的初始值,是吗?for (const char* p = mystart; *p; p++)
- 这里for
的第二个参数处的指针*p
表示这个循环存在到这个指针存在的那一刻,是吗?string(mystart,p-mystart)
- 我在 c++ reference 中找不到这个字符串用法,我知道它的结果是这些参数之间的差异,但不明白这是怎么发生的。
这几行来自下面的代码(来自另一个 SO question 的原始代码):
string line;
while (std::getline(cin, line)) { // read full line
const char *mystart=line.c_str(); // prepare to parse the line - start is position of begin of field
bool instring{false};
for (const char* p=mystart; *p; p++) { // iterate through the string
if (*p=='"') // toggle flag if we're btw double quote
instring = !instring;
else if (*p==',' && !instring) { // if comma OUTSIDE double quote
csvColumn.push_back(string(mystart,p-mystart)); // keep the field
mystart=p+1; // and start parsing next one
}
}
csvColumn.push_back(string(mystart)); // last field delimited by end of line instead of comma
}
最佳答案
bool instring{false}
表示您的想法,使用 C++11 初始化列表。c_str()
返回指向 c 风格字符串的指针,即以 null 终止。*p
将取消引用字符串末尾的 '\0',即 0,在循环中计算为false
string (const char* s, size_t n);
是正在使用的构造函数,传递起始和大小 (p-mstart)。 http://www.cplusplus.com/reference/string/string/string/
关于c++ - for循环和string函数中指针的操作和bool初值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36018767/