在 C++ 中确定字符串长度

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,我们将学习如何在 C++ 编程语言中查找用户输入的字符串的长度。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/StandardLibraryGroup(["`Standard Library`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp/BasicsGroup -.-> cpp/strings("`Strings`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") cpp/StandardLibraryGroup -.-> cpp/string_manipulation("`String Manipulation`") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`") subgraph Lab Skills cpp/strings -.-> lab-96191{{"`在 C++ 中确定字符串长度`"}} cpp/output -.-> lab-96191{{"`在 C++ 中确定字符串长度`"}} cpp/user_input -.-> lab-96191{{"`在 C++ 中确定字符串长度`"}} cpp/files -.-> lab-96191{{"`在 C++ 中确定字符串长度`"}} cpp/string_manipulation -.-> lab-96191{{"`在 C++ 中确定字符串长度`"}} cpp/code_formatting -.-> lab-96191{{"`在 C++ 中确定字符串长度`"}} end

创建一个新的 C++ 文件

~/project 目录下创建一个名为 main.cpp 的 C++ 文件。

cd ~/project
touch main.cpp

包含必要的头文件

为了在 C++ 中处理字符串,我们需要包含一些头文件。我们将在程序中使用 <iostream><string> 头文件。

#include <iostream>
#include <string>

using namespace std;

声明一个字符串变量并读取输入

我们将声明一个字符串变量并读取用户输入的字符串。

string myString;
cout<<"Enter a string: ";
getline(cin,myString);

使用 length() 函数计算字符串的长度

我们将使用 length() 函数计算用户输入的字符串的长度。

int length = myString.length();

显示字符串的长度

我们将使用 cout 语句显示上一步计算出的字符串长度。

cout<<"The length of the string is: "<< length << endl;

完整代码示例

#include <iostream>
#include <string>

using namespace std;

int main() {
    string myString;
    cout<<"Enter a string: ";
    getline(cin,myString);
    int length = myString.length();
    cout<<"The length of the string is: "<< length << endl;
    return 0;
}

总结

在本实验中,我们学习了如何在 C++ 编程语言中使用 length() 函数查找用户输入的字符串的长度。我们还学习了如何使用 cout 语句在终端中显示字符串的长度。

您可能感兴趣的其他 C++ 教程