c++ - 如何扫描 N 个字符串(使用结构)然后反向输出该字符串列表?

标签 c++ c arrays struct

使用下面的特定结构,

struct Student
{
    char first[50];
    char last[50];
    char id[20];
};

如何扫描由名字、姓氏和 ID 号组成的 N 个字符串,然后反向输出整个列表?

例如:

输入:

3
Dent Arthur 12345ABC
Prefect Ford 54321CBA
McMillan Tricia AB9876

输出:

McMillan Tricia AB9876
Prefect Ford 54321CBA
Dent Arthur 12345ABC  

这是我目前所拥有的

#include <stdio.h>
#include <string.h>



struct Student
 {
    char first[50];
    char last[50];
    char id[20];
};


int main( )
{
    int N, i;
    scanf("%d", &N);
    struct Student NAME;

    for(i=0; i<N; i++){
        scanf("%s %s %s", NAME.first[i], NAME.last[i], NAME.id[i]);

    }

    /*struct Student prefect;
    scanf("%s %s %s", &prefect.first, &prefect.last, &prefect.id);


    struct Student mcmillan;
    scanf("%s %s %s", &mcmillan.first, &mcmillan.last, &mcmillan.id);*/

    printf("\n");

    printf("%s %s %s\n", NAME.first[i], NAME.last[i], NAME.id[i]);
    printf("%s %s %s\n", NAME.first[i], NAME.last[i], NAME.id[i]);
    printf("%s %s %s\n", NAME.first[i], NAME.last[i], NAME.id[i]);

    return 0;
}

最佳答案

如果要反向打印列表(数组),

for(i=N-1; i>=0; i--){
    printf("%s %s %s\n", NAME.first[i], NAME.last[i], NAME.id[i]);

}

这解决了反转问题,尽管代码中还有一个问题。您已将 struct 的成员声明为 string 类型,并且在 main 函数中,您将它们视为字符串数组。这行不通。您可能想要一个结构对象数组。这是如何去做的:

#include <stdio.h>
#include <string.h>

struct Student
{
char first[50];
char last[50];
char id[20];
};


int main( )
{
int N, i;
scanf("%d", &N);
struct Student NAME[10];

for(i=0; i<N; i++){
    scanf("%s %s %s", NAME[i].first, NAME[i].last, NAME[i].id);

}

/*struct Student prefect;
scanf("%s %s %s", &prefect.first, &prefect.last, &prefect.id);


struct Student mcmillan;
scanf("%s %s %s", &mcmillan.first, &mcmillan.last, &mcmillan.id);*/

printf("\n");

 for(i=N-1; i>=0; i--){
printf("%s %s %s\n", NAME[i].first, NAME[i].last, NAME[i].id);

}

return 0;
}

ideone 链接:http://ideone.com/hgPjjn

关于c++ - 如何扫描 N 个字符串(使用结构)然后反向输出该字符串列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29640751/

相关文章:

c++ - 命名空间类函数

c++ - 渲染大块时出现纹理锯齿问题 : OpenGL

C 在文本文件中隔离 "only strings"

c++ - 你如何制作类对象的 vector ?

c++ - 将简单的宏作为函数参数传递给 'too few arguments in function call'

c - 如何在函数中声明数组并在C中调用该函数

c - 如何从第二个访问第一个结构-c

javascript - 将 splice 与字符串数组结合使用

javascript - 如何使用javascript获取数组的键?

c - 如何在C中对字符串数组与整数数组并行排序?没有结构体?