21xrx.com
2025-06-15 00:08:43 Sunday
登录
文章检索 我的文章 写文章
C++字符串数组的输入方法
2023-07-12 18:04:10 深夜i     37     0
C++ 字符串数组 输入 方法 数组大小

C++是一种广泛使用的编程语言,其在字符串处理方面表现出色。对于C++开发人员来说,处理字符串数组是一个基本的技能,需要熟练掌握输入方法。下面是C++字符串数组的输入方法,希望对学习C++的同学有所帮助。

首先,我们可以使用cin输入字符串数组。这是一个简单的示例:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  const int SIZE = 3;
  string strArray[SIZE];
  for (int i = 0; i < SIZE; i++) {
    cout << "Enter string #" << i + 1 << ": ";
    cin >> strArray[i];
  }
  cout << "The strings you entered are: " << endl;
  for (int i = 0; i < SIZE; i++) {
    cout << strArray[i] << endl;
  }
  return 0;
}

在上面的示例中,我们首先定义一个大小为3的字符串数组。使用for循环,我们要求用户输入字符串,并将其存储在字符串数组中。用户输入的字符串将被保存在cin读取的string中,然后存储在字符串数组中。最后,我们循环输出这些字符串。

此外,我们也可以使用getline()函数来输入字符串数组。getline()函数以行为单位读取输入,并存储在一个字符串中。这是另一个简单的示例:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  const int SIZE = 3;
  string strArray[SIZE];
  for (int i = 0; i < SIZE; i++) {
    cout << "Enter string #" << i + 1 << ": ";
    getline(cin, strArray[i]);
  }
  cout << "The strings you entered are: " << endl;
  for (int i = 0; i < SIZE; i++) {
    cout << strArray[i] << endl;
  }
  return 0;
}

在上面的示例中,我们使用getline()函数读取用户输入的字符串,并将其存储在字符串数组中。与之前一样,我们使用for循环遍历该数组,并输出存储在字符串数组中的字符串。

总之,C++字符串数组的输入方法非常简单。我们可以使用cin或getline()函数读取用户输入的字符串,并将其存储在字符串数组中。学习这些方法可以帮助C++开发人员更高效地处理字符串数组。

  
  

评论区