【问题标题】:How to input data from user into 2d array and cout to user c++如何将用户的数据输入二维数组并输出到用户c++
【发布时间】:2020-04-18 04:18:06
【问题描述】:

所以我对 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)

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

【问题讨论】:

  • favBands[i][j] = band;favBands[i][j] = song; 都写入同一个位置。如果您使用调试器或在一张纸上逐步完成程序,其余的应该能够弄清楚。

标签: c++ arrays multidimensional-array


【解决方案1】:

您只需要一个 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;

  } 
 }

【讨论】:

    【解决方案2】:

    请允许我建议使用两个单独的数组而不是二维数组,一个用于乐队,一个用于歌曲,然后计算歌曲,如下所示:

        #include <iostream>
        using namespace std;
        int main() {
            string favBands[10];
            string favSongs[10];
    
            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] = band;
                cout << "Enter " << favBands[i] << "'s best song:\n" << endl;
                cin >> song;
                favSongs[i] = song;
                cout << "Your favorite song by " << favBands[i] << " is " << favSongs[i] << ".\n";
            }
        }
    

    虽然乐队和歌曲都是字符串,但二维数组并不是最适合此类问题。

    【讨论】:

    • 应该可以。考虑使用一个聚合乐队和歌曲的结构数组。当搜索和排序进入作业时,几乎总是使簿记更易于管理。
    • 这样做会容易得多,但我正在尝试使用二维数组进行练习,但感谢您的建议!