使用下面的特定结构,
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/