Home  >  Article  >  Backend Development  >  How to input array in c++

How to input array in c++

下次还敢
下次还敢Original
2024-05-01 12:36:15324browse

There are many ways to enter an array in C, the most commonly used ones include: using std::cin: enter the array elements one by one. Use array initializer: Initialize array elements directly. Using getline and isringstream: Read from a line of input and convert to an array.

How to input array in c++

How to enter an array in C

There are many ways to enter an array in C. The most common methods are listed below:

1. Use std::cin

<code class="cpp">int main() {
  int arr[10]; // 声明一个长度为 10 的数组

  // 使用 std::cin 输入数组元素
  for (int i = 0; i < 10; i++) {
    std::cin >> arr[i];
  }

  return 0;
}</code>

2. Use an array initializer

<code class="cpp">int main() {
  // 使用数组初始化器创建数组
  int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

  return 0;
}</code>

3. Use getline

<code class="cpp">int main() {
  std::string input;
  std::getline(std::cin, input); // 从标准输入读取一行

  // 将输入字符串转换为数组
  std::istringstream iss(input);
  int arr[10];
  for (int i = 0; i < 10; i++) {
    iss >> arr[i];
  }

  return 0;
}</code>

The above is the detailed content of How to input array in c++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn