在 C++ 中标记字符串

Tokenizing a string in C++

描述: 在 C++ 中构建用于标记化字符串(包括空格)的基本代码。

主要思想: 调用一个本地函数,该函数使用空值作为开头来计算字符串中的所有空格。

问题:在到达第二个令牌之前提前终止。

#include "stdafx.h"
#include <iostream>
#include <cstring>

using namespace std;

char *next_token = NULL;

int count_spaces(const char *p);

char *p;

int main() {
    char s[81];

    cout << "Input a string : ";
    cin.getline(s, 81);

    p = strtok_s(s, ", ", &next_token);

    while (p != nullptr) {
        cout << p << endl;
        p = strtok_s(nullptr, ", ", &next_token);
    }

    count_spaces(p);

    cout << count_spaces(p);

    return 0;
}

int count_spaces(const char *p) {
    int number = 0, len;
    if (p == NULL) {
        return 0;
    }

    while (*p) {
        if (*p == '1')
            len = 0;
        else if (++len == 1)
            number++;
        p++;
    }
}

如有任何帮助,我们将不胜感激。

您程序的标记化部分有效。但是当你调用 count_spaces(p) 时,p 总是 NULL (或者 nullptr 几乎是一样的)。

也许你想要这个(我省略了标记化部分):

#include <iostream>
#include <cstring>

using namespace std;

int count_spaces(const char *p);

int main() {
  char s[81];
  cout << "Input a string : ";
  cin.getline(s, sizeof s);      // using sizeof s is better than repeating "81"

  cout << "Number of spaces in string: " << count_spaces(s) << endl;
  return 0;
}

int count_spaces(const char *p) {
  if (p == NULL) {
    return 0;
  }

  int nbofspaces = 0;

  while (*p) {
    if (*p == ' ') { 
      nbofspaces++;
    }
    p++;
  }

  return nbofspaces;
}

免责声明:这是糟糕的 C++ 代码。这更像是您在 C 中所做的,但此代码尽可能贴近 OP 的原始代码。