c++ - for循环和string函数中指针的操作和bool初值

标签 c++ arrays string pointers

有人可以解释/确认下面几行的意思吗?

  1. bool instring{false}; - 这意味着 false 是这个变量的初始值,是吗?
  2. for (const char* p = mystart; *p; p++) - 这里 for 的第二个参数处的指针 *p 表示这个循环存在到这个指针存在的那一刻,是吗?
  3. 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
}

最佳答案

  1. bool instring{false} 表示您的想法,使用 C++11 初始化列表。
  2. c_str() 返回指向 c 风格字符串的指针,即以 null 终止。 *p 将取消引用字符串末尾的 '\0',即 0,在循环中计算为 false
  3. 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/

相关文章:

python - C 中的字符串格式化

string - 将数字转换为字母

C++ limits.h 定义

c++ - 如何实现正则表达式

ios - 几天后我的 iOS 应用程序中的数据消失了

java - 无法获得沙漏算法的精确结果

javascript - 将单词列表转换为数组

string - $d 在 printf 中做什么?

c++ - Visual Studio - C++ - 以 32 位或 64 位构建和运行应用程序 - 从适当的 ProgramFiles 目录加载 DLL

c++打包和解包参数包以在没有STL的情况下调用匹配的函数指针