所以我对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 0
和index 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;
}
}
[允许我建议使用两个单独的数组而不是2D数组,一个用于乐队,一个用于歌曲,然后像这样对歌曲进行提示:
#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";
}
}
尽管乐队和歌曲都是弦乐,但二维数组并不是真的最适合这种类型的问题。
您只需要进行一次循环,就将循环变量[i][0]
的频段存储在[i][1]
,并将歌曲存储在i
。