c++ - 如何将数据从用户输入到2D数组中,并输出到用户C++

标签 c++ arrays multidimensional-array

因此,我对使用C++的2d数组相当陌生,我知道自己做错了什么,但不确定自己做什么。

#include <iostream>
using namespace std;

int main(){
  string favBands[10][2];

  cout << "Welcome to the favorite band printer outer!" << endl;

  int count = 1;
  string band;
  string song;
  for(int i = 0; i < 10; i++){
    for(int j = 1; j < 2; j++){
      cout << "Enter your number " << count << " band:\n" << endl;
      count += 1;
      cin >> band;
      favBands[i][j] = band;
      cout << "Enter " << favBands[i][j] << "'s best song:\n" << endl;
      cin >> song;
      favBands[i][j] = song;
    }
  }
}

我想请用户输入10个最喜欢的乐队,然后从一对中要求他们最喜欢的歌曲。因此,例如:
Enter your number 1 favorite band:

Black Eyed Peas (user input)

Enter your favorite Black Eyed Peas song:

Boom Boom Pow (user input)

我能够完成所有这些操作,但是当我尝试将阵列打印给用户时,问题就来了。我认为我的问题可能在于如何将用户数据输入到数组中,但我不确定如何解决它。谢谢!

最佳答案

您只需要一个for循环。看到我们正在为10个用户存储数据。对于每个用户,我们分别在index 0index 1处获取两个数据。因此,我们不需要第二个for循环。请遵守代码并询问您是否还有任何困惑。我也很乐意弄清楚。

#include <iostream>
using namespace std;

 int main(){
string favBands[10][2];

cout << "Welcome to the favorite band printer outer!" << endl;

int count = 1;
string band;
string song;
for(int i = 0; i < 10; i++)
{
  cout << "Enter your number " << count << " band:\n" << endl;
  count += 1;
  cin >> band;
  favBands[i][0] = band;



  cout << "Enter " << favBands[i][0] << "'s best song:\n" << endl;
  cin >> song;
  favBands[i][1] = song;

  } 
 }

关于c++ - 如何将数据从用户输入到2D数组中,并输出到用户C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61284170/

相关文章:

java - 如何在Java中将2d集合转换为1d?

javascript - 如何从数组中的数组中删除空值?

c# - 二维数组插值

使用 strncpy 将文件逐行复制到 char 数组中

c++ - 无法从字符串流接收信息

C++ 如何比较类

c++ - 在数组c++上调用排序函数

c++ - std::cout 正在降低 CPU 使用率?

C++ 在 vector 中添加 double 元素

c# - string.split 返回一个 string[] 我想要一个 List<string> 是否有一个衬垫可以将数组转换为列表?