C语言代码输出空白而非输入内容问题求助
C语言代码无法正确打印姓名问题修复
编写的C语言代码原本要实现输入姓名并打印的功能,但实际输出空白内容。怀疑是数据类型错误导致,之前打印整数正常,现在处理姓名时出现问题,认为核心问题出在printStack函数中。
原代码
#include <stdio.h> #include <stdlib.h> #define SIZE 25 char stack[SIZE]; int top=-1; int isFull(){ if (top>=SIZE-1){ return 1; } return 0; } struct n{ n * next; char data; }; typedef n node; void printStack(char person){ printf("Entered persons: \n"); for(int i=0;i<=top;i++) printf("%c\n",stack[person]); printf("\n"); } void push(node * root, char person){ if(root == NULL || isFull()){ root = (node *)malloc(sizeof(node)); root -> data = person; root -> next = NULL; stack[++top]=person; } node * iter = root; while(iter->next !=NULL || isFull()){ iter = iter -> next; stack[++top]=person; } } int main() { int pick; char person; node * s=NULL; while (1){ printf("1 - Add person\n"); printf("2 - Show persons\n"); printf("3 - Exit\n"); scanf("%d",&pick); switch (pick){ case 1: printf ("Person name: "); scanf("%s",&person); push(s, person); break; case 2: printStack(person); break; case 3: exit(0); break; } } return 0; }
核心错误分析
- 数据类型与输入不匹配:
char person;是单个字符变量,但用scanf("%s", &person);读取字符串,会直接导致缓冲区溢出,破坏内存。要存储姓名必须用字符数组,比如char person[SIZE];。 - printStack函数逻辑完全错误:
- 函数参数
char person毫无意义,遍历栈时错误地用stack[person](用person的ASCII值作为数组索引),正确写法应该是stack[i]来遍历每个栈元素。 - 该函数不需要传入person参数,直接基于全局变量
top遍历栈即可。
- 函数参数
- push函数逻辑混乱:
- 同时混用链表和栈存储数据,逻辑冲突,且
root是传值调用,修改root不会影响main函数中的s指针,需要传指针的指针node **root。 - 循环条件
iter->next !=NULL || isFull()错误,且每次循环重复将同一个person压入栈,逻辑完全不符合“添加姓名”的需求。
- 同时混用链表和栈存储数据,逻辑冲突,且
- 设计错误:当前栈和链表都只能存储单个字符,但需求是存储姓名(字符串),需要调整数据结构,比如用二维字符数组作为栈,或者让链表节点存储字符串指针。
修正后的代码示例(基于栈存储字符串)
#include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 25 #define NAME_LEN 50 // 用二维数组存储多个姓名 char stack[SIZE][NAME_LEN]; int top = -1; int isFull() { return top >= SIZE - 1; } int isEmpty() { return top == -1; } // 压入姓名到栈 void push(const char *name) { if (isFull()) { printf("Stack is full!\n"); return; } strcpy(stack[++top], name); } // 打印所有姓名 void printStack() { if (isEmpty()) { printf("No persons entered yet!\n"); return; } printf("Entered persons:\n"); for (int i = 0; i <= top; i++) { printf("%s\n", stack[i]); } printf("\n"); } int main() { int pick; char person[NAME_LEN]; while (1) { printf("1 - Add person\n"); printf("2 - Show persons\n"); printf("3 - Exit\n"); // 处理scanf后的换行符残留问题 while (getchar() != '\n'); scanf("%d", &pick); switch (pick) { case 1: printf("Person name: "); // 读取姓名,支持带空格的输入 while (getchar() != '\n'); fgets(person, NAME_LEN, stdin); // 去掉fgets读取的换行符 person[strcspn(person, "\n")] = '\0'; push(person); break; case 2: printStack(); break; case 3: exit(0); default: printf("Invalid option!\n"); } } return 0; }
内容的提问来源于stack exchange,提问作者Emir
相关产品推荐
相关产品推荐

