从键盘输入一串字符串,求此字符串的长度。c++代码
时间: 2023-10-04 09:13:49 浏览: 117
可以使用C++中的`string`类型的`length`函数来获取从键盘输入的字符串的长度,示例代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cout << "Please enter a string: ";
cin >> str;
int len = str.length();
cout << "The length of the string is: " << len << endl;
return 0;
}
```
输入一个字符串后,输出结果为:
```
Please enter a string: Hello, world!
The length of the string is: 13
```
相关问题
输入一串字符串,求此字符串的长度。c++语言
好的,这是C++语言代码实现:
```
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[100];
// 输入字符串
cout << "请输入字符串:" << endl;
cin.getline(str, 100);
// 计算字符串长度
int len = strlen(str);
// 输出字符串长度
cout << "字符串长度为:" << len << endl;
return 0;
}
```
以上代码实现了从键盘输入字符串,然后计算字符串长度并输出。其中,`strlen` 函数用于计算字符串长度,需要引入头文件 `cstring`。
c++从键盘输入一个字符串,删除字符串中的所有空格
可以使用字符串的特性来实现删除空格的功能,具体步骤如下:
1. 从键盘输入字符串并存储到一个字符数组中。
2. 定义一个新的字符数组,用于存储删除空格后的字符串。
3. 遍历原始字符串,将非空格字符添加到新的字符数组中。
4. 最后在新的字符数组后面添加一个结束符 '\0'。
以下是一个 C 语言的代码示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100], new_str[100];
int i, j = 0;
printf("Enter a string: ");
gets(str);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] != ' ') {
new_str[j] = str[i];
j++;
}
}
new_str[j] = '\0';
printf("Modified string: %s\n", new_str);
return 0;
}
```
需要注意的是,上述代码中使用了 gets() 函数读取输入字符串,但该函数存在安全漏洞,建议使用 fgets() 函数代替。另外,如果输入的字符串长度超过了数组的大小,可能会导致程序崩溃,因此需要进行输入长度的检查。
阅读全文
相关推荐













