如何指定要在数组中输出的值?这是我的代码
#include<iostream.h>
#include<conio.h>
#include <string.h>
int main(){
clrscr();
char name[5][80] ={ "Lester", "Charmander", "Squirtle", "Bulbasor","Pikachu"};
int a[5];
int i;
int n;
for(n=0; n<=10; n++){
cout <<"Enter your student number: ";
cin>>a[i];
if(a[i]==1) {cout<<"Lester\n"; }
if(a[i]==2) {cout<<"Charmander\n"; }
if(a[i]==3) {cout<<"Squirtle\n"; }
if(a[i]==4) {cout<<"Bulbasor\n";}
if(a[i]==5) {cout<<"Pikachu\n"; break;}
}
clrscr();
int k;
for(k=0; k<6; k++){
cout << name[k]<<"\n";
}
return 0;
}下面是上面代码的输出
Enter your student number: 1
Lester
Enter your student number:2
Charmander
Enter your student number:5
Pikachu
Lester
Charmander
Squirtle
Bulbasor
Pikachu它输出数组的所有值。但是我想要一个应该是这样的输出
Enter your student number: 1
Lester
Enter your student number:2
Charmander
Enter your student number:5
Pikachu
Lester
Charmander
Pikachu发布于 2014-03-17 16:34:59
免责声明:我以前没有使用过涡轮C++,但据我所知,它本质上是带有C++特性子集的C。
我不确定你是否有@rockStar的版本可以工作,所以我会在你的main上发布一个稍微干净和工作的版本。
int main(){
clrscr();
char name[5][80] ={ "Lester", "Charmander", "Squirtle", "Bulbasaur","Pikachu"};
int numbers[10]; //'temporary array' to store the list of numbers
int n;
int num = 0;
for(n=0; n<=10 && num != 5; n++){
cout <<"Enter your student number: ";
cin >> num;
if(num > 0 && num < 6){
cout << name[num-1] << '\n';
numbers[n] = num;
}
}
clrscr();
int i;
for(i=0; i<n; i++){ //there were n entries
cout << name[numbers[i] -1]<<"\n";
}
return 0;
}它生成所请求的输出(减去第一行之后的所有内容的缩进)。
发布于 2014-03-17 09:30:19
我已经添加了我的代码并包含了一个注释,希望这个帮助,如果有一些错误,请提供,因为我没有编译器。
#include<iostream.h>
#include<conio.h>
#include <string.h>
int main(){
clrscr();
char name[5][80] ={ "Lester", "Charmander", "Squirtle", "Bulbasor","Pikachu"};
int a[5];
//temporary array
int temp_array[10];
int i;
int n;
for(n=0; n<=10; n++){
cout <<"Enter your student number: ";
cin>>a[i];
if(a[i]==1) {cout<<"Lester\n"; temp_array[a[i]] = a[i]; }
if(a[i]==2) {cout<<"Charmander\n"; temp_array[a[i]] = a[i];}
if(a[i]==3) {cout<<"Squirtle\n"; temp_array[a[i]] = a[i];}
if(a[i]==4) {cout<<"Bulbasor\n"; temp_array[a[i]] = a[i];}
if(a[i]==5) {cout<<"Pikachu\n"; temp_array[a[i]] = a[i]; break;}
}
clrscr();
int k;
for(k=0; k<6; k++){
if(temp_array[k] != '') //checks if the value of that array is not empty
cout << temp_array[k]<<"\n";
}
return 0;
}https://stackoverflow.com/questions/22450316
复制相似问题