在C++; 描述: C++中的基本代码,用于标记字符串(包括空白)。
主要思想是:调用一个本地函数,该函数使用字符串中的空值开始计算字符串中的所有空格 问题:在到达第二个令牌之前提前终止在C++; 描述: C++中的基本代码,用于标记字符串(包括空白)。,c++,tokenize,C++,Tokenize,主要思想是:调用一个本地函数,该函数使用字符串中的空值开始计算字符串中的所有空格 问题:在到达第二个令牌之前提前终止 #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]
#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++;
}
}
#包括“stdafx.h”
#包括
#包括
使用名称空间std;
char*next_token=NULL;
int count_空间(const char*p);
char*p;
int main(){
chars[81];
cout程序的标记化部分可以工作。但是当您调用count\u spaces(p)
时,p
总是NULL
(或者nullptr
,两者基本相同)
也许您想要这个(我省略了标记化部分):
#包括
#包括
使用名称空间std;
int count_空间(const char*p);
int main(){
chars[81];
CUT< COD> CONTHYSPACE 不计算空间……并且不返回任何有趣的值。仔细阅读编译器所说的…代码严重损坏。这不是。无论如何,验证你的假设,关于如何确定某事物是空白。你的C++代码没有编译这些错误。你从未成功过CRE。我用了这个程序。我用的是MVStudio 17,它在那里运行得很好,在它调用输出为零的本地函数之前一切都正常。我如何操作本地函数,使它能够计算字符串中的所有非字符?你读过并理解编译器发出的警告了吗?我有点喜欢它:)
看起来像一个真正的效率NT C++程序员将do..davidC.RANKIN当然不是C++代码,它只适用于OP的原始代码。它唯一缺少的是一些古怪的模板使它不适合于<代码> String < /C> >或 cString < /C> >。我不认为有C++的计数方式<代码>空间< /C> >,除非你只使用<代码>字符串<代码>并使用基于范围的循环(但它仍然可以归结为计算空格)@MichaelWalz Michael非常感谢您的评论/解决方案,这解决了我的问题。在您发布给她的代码第26行中,我还有一个小问题:if(*p=''){,编译器如何识别撇号中的空格?当我将值更改为0时,代码没有正常工作。编译器后面会发生什么?@Mabadai编译器识别撇号之间的空格,因为是撇号之间的空格,就像它识别撇号之间的a一样('a'
).撇号之间的字母相当于该字母的ASCII码,例如,书写'A'
与书写65
相同。
#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;
}