指定要在数组中输出的值

时间:2014-03-17 09:09:28

标签: c++ arrays turbo-c++

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

#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

2 个答案:

答案 0 :(得分:0)

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

#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;
}

答案 1 :(得分:0)

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

它产生您请求的输出(减去第一行之后的所有内容的缩进)。