21xrx.com
2024-06-03 01:27:58 Monday
登录
文章检索 我的文章 写文章
C++ 字符串数组输入方法
2023-07-09 05:46:21 深夜i     --     --
C++ 字符串数组 输入方法

在 C++ 中,字符串数组是一种常见的数据类型,用于存储一组字符串。有时,我们需要从用户输入中获取一组字符串,例如一组姓名或一组电子邮件地址。下面介绍几种常见的方法。

1. 使用 for 循环输入

这种方法比较简单,可以使用 for 循环依次获取每个字符串。代码如下:


#include<iostream>

using namespace std;

int main()

{

  const int SIZE = 5; //定义字符串数组大小

  string names[SIZE]; //定义字符串数组

  cout<<"请输入 "<<SIZE<<" 个姓名:"<<endl;

  for(int i=0; i<SIZE; i++)

  {

    cin>>names[i];

  }

  cout<<"输入的姓名为:"<<endl;

  for(int i=0; i<SIZE; i++)

  {

    cout<<names[i]<<endl;

  }

  return 0;

}

2. 使用 getline 函数输入

如果输入的字符串中包含空格或其他特殊字符,使用上述方法可能会出现问题。此时,可以使用 getline 函数获取一行字符串。代码如下:


#include<iostream>

using namespace std;

int main()

{

  const int SIZE = 5; //定义字符串数组大小

  string emails[SIZE]; //定义字符串数组

  cout<<"请输入 "<<SIZE<<" 个电子邮件地址:"<<endl;

  for(int i=0; i<SIZE; i++)

  {

    getline(cin, emails[i]);

  }

  cout<<"输入的电子邮件地址为:"<<endl;

  for(int i=0; i<SIZE; i++)

  {

    cout<<emails[i]<<endl;

  }

  return 0;

}

3. 使用 stringstream 输入

如果需要从一个字符串中分离出多个子串,可以使用 stringstream 类。代码如下:


#include<iostream>

#include<sstream>

using namespace std;

int main()

{

  string str = "Tom;Jerry;Lucy;Bob;Alice"; //定义原始字符串

  const int SIZE = 5; //定义字符串数组大小

  string names[SIZE]; //定义字符串数组

  stringstream ss(str); //将原始字符串转换为 stringstream 对象

  string temp;

  int i = 0;

  while(getline(ss, temp, ';')) //使用 getline 函数分离子串

  {

    names[i] = temp;

    i++;

  }

  cout<<"分离的姓名为:"<<endl;

  for(int i=0; i<SIZE; i++)

  {

    cout<<names[i]<<endl;

  }

  return 0;

}

以上是 C++ 字符串数组输入的几种常见方法,不同的方法适用于不同的情况。需要根据具体需求选择合适的方法。

  
  

评论区

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