#include<bits/stdc++.h> using namespace std; int main(){ char s[105]={}; int count = 0; cin.getline(s,105); for(int i=0;i<strlen(s);i++){ if(s[i]==' ') count++; } cout<<count; return 0; }
时间: 2023-06-23 21:10:22 浏览: 89
这是一个 C++ 的程序,实现的功能是统计输入的字符串中空格的个数。
具体来说,程序定义了一个字符数组 s,长度为 105,用于存储输入的字符串。然后通过 `cin.getline(s,105)` 语句读入字符串,该语句可以读入一行字符串(包括空格),并将其存储到 s 中。
接下来,程序遍历字符串 s 的每一个字符,如果该字符是空格,则将计数器 count 加 1。
最后,程序输出 count 的值,即输入字符串中空格的个数。
需要注意的是,程序中使用了 C++ 标准库中的函数 strlen,该函数可以获取一个字符串的长度。
相关问题
#include <bits/stdc++.h> using namespace std; int main() { char s[]="hello C++ world"; char *d; char c[]=" "; d=&c; char *p; p=strtok(s,d); while (p!=NULL) { cout <<p <<endl; p=strtok(NULL,d); } return 0; }
在这段代码中,你尝试将指向字符数组的指针 `&c` 赋值给字符指针 `d`,这是不允许的,因为两者类型不同。正确的做法是将 `d` 声明为字符数组类型,即 `char d[] = " "`。这样就可以将空格字符数组的地址赋值给 `d`。修改后的代码如下:
```
#include <bits/stdc++.h>
using namespace std;
int main() {
char s[] = "hello C++ world";
char d[] = " ";
char *p;
p = strtok(s, d);
while (p != NULL) {
cout << p << endl;
p = strtok(NULL, d);
}
return 0;
}
```
这段代码的功能是将字符串 `s` 按照空格进行分割,并输出分割后的结果。注意,这段代码使用了 `strtok()` 函数进行字符串分割操作。
#include<bits/stdc++.h> using namespace std; int main() { char s1[200],s2[200]; int a[200],b[200],c[400] cin>>s1>>s2; int fushu1=0; if (s1[0]=='-'){ fushu=1; } cout<<"100"; return 0; }他有什么错误
该程序存在以下错误:
1. 变量名错误:在判断 s1 是否为负数时,变量名应为 fushu1 而不是 fushu。
2. 缺少分号:在定义变量 c 后,缺少分号。
3. 数组越界:在输入字符串时,应保证输入的字符串长度不超过数组长度,否则会导致数组越界。
4. 缺少空格:在定义变量 c 后,应该在 int 和 c 之间添加空格。
修改后的程序如下所示:
```c++
#include<bits/stdc++.h>
using namespace std;
int main() {
char s1[200], s2[200];
int a[200], b[200], c[400];
cin >> s1 >> s2;
int fushu1 = 0;
if (s1[0] == '-') {
fushu1 = 1;
}
cout << "100";
return 0;
}
```