【问题标题】:Operations on pointers in for loop and string function and bool initial valuefor循环和字符串函数中的指针和bool初始值的操作
【发布时间】:2016-07-01 08:02:00
【问题描述】:

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

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

【问题讨论】:

    标签: c++ arrays string pointers


    【解决方案1】:
    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/

    【讨论】:

      【解决方案2】:
      1. 正确。这是一种相对较新的统一初始化语法
      2. 当指针 p 指向零值时循环退出
      3. 字符串使用了两个迭代器的构造函数,它也可以接受两个指针。新字符串包含从第一个指针(含)开始到第二个(计算的)指针(不含)的所有内容。

      【讨论】:

        【解决方案3】:
        1. bool instring{false}; 这称为列表初始化,从 C++11 开始可用。你可以在这里找到更多信息:http://en.cppreference.com/w/cpp/language/list_initialization

        2. for (const char* p = mystart; *p; p++) 只要你的字符串中还有字符,它就会循环。

        3. string(mystart,p-mystart) 这是 string() 的重载构造函数。在您的情况下,它会复制第一个 p-mystart 字符。您可以在此处找到更多相关信息(列表中的第 5 位):http://www.cplusplus.com/reference/string/string/string/

        【讨论】:

          【解决方案4】:

          对于第 1 项,也许你的意思是 bool instring(false); (括号而不是花括号)。是的,这意味着将 instring 初始化为值 'false';

          对于第 2 项,*p 为 0 表示您已到达以空字符结尾的字符串的末尾。因此,当您到达字符串的末尾时,循环将停止。

          对于第 3 项,第一个 arg to string 是一个字符串,第二个是一个整数(数字)值,表示字符串的长度或字符串的一部分。

          【讨论】:

            猜你喜欢
            • 2010-12-01
            • 2017-10-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-06-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多