指定要在数组中输出的值

specifying the value to be outputted in an array

本文关键字:输出 数组      更新时间:2023-10-16

如何指定要在数组中输出的值?这是我的代码

#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<<"Lestern"; }
    if(a[i]==2) {cout<<"Charmandern"; }
    if(a[i]==3) {cout<<"Squirtlen"; }
    if(a[i]==4) {cout<<"Bulbasorn";}
    if(a[i]==5) {cout<<"Pikachun";  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

免责声明:我以前没有使用过Turbo 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;
}

生成您所要求的输出(减去第一行之后的缩进)。

我已经添加了我的代码并包括一个注释,希望这有帮助,如果有一些错误,请提供,因为我没有编译器与我。

#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<<"Lestern"; temp_array[a[i]] = a[i]; }
    if(a[i]==2) {cout<<"Charmandern"; temp_array[a[i]] = a[i];}
    if(a[i]==3) {cout<<"Squirtlen"; temp_array[a[i]] = a[i];}
    if(a[i]==4) {cout<<"Bulbasorn"; temp_array[a[i]] = a[i];}
    if(a[i]==5) {cout<<"Pikachun";  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;
}