21xrx.com
2024-06-03 03:19:26 Monday
登录
文章检索 我的文章 写文章
C++ 如何输入字符串(string)?
2023-07-03 13:50:59 深夜i     --     --
C++ 输入 字符串 string 方法

在C++中,可以使用标准库中的string类来输入字符串。string类提供了许多成员函数,可以方便地输入、输出和操作字符串。

首先,要使用string类,需要包含头文件 。然后,可以使用std命名空间来使用string类。例如,可以定义一个string变量并将其初始化为用户输入的字符串,代码如下:


#include <iostream>

#include <string>

using namespace std;

int main() {

  string input;

  cout << "Enter a string: ";

  getline(cin, input);

  cout << "You entered: " << input << endl;

  return 0;

}

在上面的代码中,输入的字符串通过getline函数来获取。getline函数接受两个参数:要读取的输入流和存储输入的字符串变量。在上面的代码中,输入流为cin,存储输入的字符串变量为input。

需要注意的是,getline函数会读取整行输入,包括空格和制表符。如果想要仅读取一个单词,可以使用输入运算符>>来读取,例如:


#include <iostream>

#include <string>

using namespace std;

int main()

  string input;

  cout << "Enter a word: ";

  cin >> input;

  cout << "You entered: " << input << endl;

  return 0;

值得一提的是,如果需要输入含有空格的字符串,那么就需要用到getline函数,否则空格后的内容将被当做另一个输入被程序读取。

总的来说,使用string类来输入字符串非常方便,能够满足各种输入场景的要求。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复