描述:在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
)。