Home  >  Article  >  Backend Development  >  How to input two arrays in c++

How to input two arrays in c++

下次还敢
下次还敢Original
2024-04-22 17:42:171123browse

The methods of inputting two arrays in C are: input element by element: use a for loop to read the array elements one by one. Row input: Read the entire row of data and split it into an array. fill_n function: fills the array elements with the specified value. iota function: fills continuous values ​​into an array.

How to input two arrays in c++

How to input two arrays in C

Direct input method

  • for loop: Use the for loop to input the elements in the two arrays one by one.
<code class="cpp">int main() {
  int arr1[5], arr2[5];
  cout << "Enter elements for arr1: ";
  for (int i = 0; i < 5; i++) {
    cin >> arr1[i];
  }
  cout << "Enter elements for arr2: ";
  for (int i = 0; i < 5; i++) {
    cin >> arr2[i];
  }
  return 0;
}</code>
  • getline: Use the getline function to read the entire line and then split the elements into an array.
<code class="cpp">int main() {
  int arr1[5], arr2[5];
  string line1, line2;
  cout << "Enter elements for arr1: ";
  getline(cin, line1);
  cout << "Enter elements for arr2: ";
  getline(cin, line2);
  istringstream iss1(line1);
  istringstream iss2(line2);
  for (int i = 0; i < 5; i++) {
    iss1 >> arr1[i];
    iss2 >> arr2[i];
  }
  return 0;
}</code>

Function input method

  • fill_n: Use the fill_n function to fill the array with the specified value.
<code class="cpp">int main() {
  int arr1[5], arr2[5];
  fill_n(arr1, 5, 0);  // 初始化 arr1 为 0
  fill_n(arr2, 5, 1);  // 初始化 arr2 为 1
  return 0;
}</code>
  • iota: Use the iota function to fill consecutive values ​​into an array.
<code class="cpp">int main() {
  int arr1[5], arr2[5];
  iota(arr1, arr1 + 5, 1);  // 将 1-5 填充到 arr1
  iota(arr2, arr2 + 5, 6);  // 将 6-10 填充到 arr2
  return 0;
}</code>

The above is the detailed content of How to input two arrays 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