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

How to input two arrays in c++

下次还敢
Release: 2024-04-22 17:42:17
Original
1202 people have browsed it

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>
Copy after login
  • 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>
Copy after login

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>
Copy after login
  • 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>
Copy after login

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!

Related labels:
c++
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template