我对C编程很陌生,我只是在做家庭作业,但问题是,我不明白为什么选择"Visualizar platos del dia“会输出奇怪的符号,而不是我输入的卡格结构。
#include <stdio.h>
#include <string.h>
#include <strings.h>
struct platos{
char aperitivo[40];
char plato1[40];
char plato2[40];
char postre[40];
char bebida1[40];
char bebida2[40];
char bebida3[40];
};
void cargar(struct platos a);
void vis(struct platos a);
void emit(struct platos a);
int main(){
int a=0, b=0;
struct platos plato;
do{
printf("Bienvenido a restaurante 'Senior bigotes'\n\n");
printf("1:Cargar platos del dia\n");
printf("2:VIsualizar platos del dia\n");
printf("3:Emitir comanda y factura\n");
printf("4:Salir\n");
scanf("%d", &a);
switch(a){
case 1: cargar(plato);
break;
case 2: vis(plato);
break;
case 3: emit(plato);
break;
case 4:
b++;
break;
}
}while(b<1);
return 0;
}
void cargar(struct platos a){
printf("Ingrese aperitivo\n");
__fpurge(stdin);
gets(a.aperitivo);
printf("Ingrese plato 1\n");
__fpurge(stdin);
gets(a.plato1);
printf("Ingrese plato 2\n");
__fpurge(stdin);
gets(a.plato2);
printf("Ingrese postre\n");
__fpurge(stdin);
gets(a.postre);
printf("Ingrese bebida 1\n");
__fpurge(stdin);
gets(a.bebida1);
printf("Ingrese bebida 2\n");
__fpurge(stdin);
gets(a.bebida2);
printf("Ingrese bebida 2\n");
__fpurge(stdin);
gets(a.bebida3);
}
void vis(struct platos a){
printf("\nAperitivo: %s", a.aperitivo);
printf("\nPlato 1: %s", a.plato1);
printf("\nPlato 2: %s", a.plato2);
printf("\nPostre: %s", a.postre);
printf("\nBebidas: %s | %s | %s\n", a.bebida1, a.bebida2, a.bebida3);
int c = getchar();
}
void emit(struct platos a){
printf("\nAperitivo: %s $10", a.aperitivo);
printf("\nPlato 1: %s $25", a.plato1);
printf("\nPlato 2: %s $35", a.plato2);
printf("\nPostre: %s $20", a.postre);
printf("\nBebidas: %s | %s | %s $15\n", a.bebida1, a.bebida2, a.bebida3);
printf("Total: $105");
int c = getchar();
}我用的是manjaro和视觉代码。我问老师,他想让我调试代码,但是他想知道如何在可视化代码中进行调试。有什么帮助吗?
发布于 2022-06-25 00:13:03
如果您是指Visual代码,则它有一个Run菜单项,其中包含调试项,如Toggle Breakpoint和Start Debugging。
第一个可以用于要开始调试的语句,第二个可以用于开始运行代码。一旦命中断点,屏幕上就应该有一个小面板,其中包含用于继续、跨过、进入等等的控件:

如果您在这些控件上悬停,它还应该显示您可以使用的等效键盘命令。
但是,您应该知道,对于当前的问题,结构是以C格式传递的,而不是通过引用传递的。这意味着cargar函数获取plato的副本并填充该副本的字段。
然后,当从cargar返回时,该副本将被丢弃,将原始的plato保留在创建时给出的任意字段。因此,当随后将其传递给vis或emit时,您将不会看到输入的数据。
最简单的解决方案可能是将指针(&plato)传递给cargar,并使用->而不是.访问该函数中的字段。换句话说,类似的内容(请参阅下面关于我为什么使用fgets()的说明):
switch (a) {
case 1: cargar(&plato); break;和
void cargar(struct platos const *a_ptr){
printf("Ingrese aperitivo\n");
__fpurge(stdin);
fgets(a_ptr->aperitivo, sizeof(a_ptr->aperitivo), stdin);
// And so on for the other fields ...在const之前的特定*a_ptr应用于指针值本身,而不是指针后面的值。您需要能够更改值,因为这是函数的全部用途。
但是,我也会为vis()和emit()做类似的事情,这样就不会复制大型结构,但是我会使用(例如):
void vis(const struct platos const *plato) {为了说明清楚,指针和指针后面的值都不会改变。
而且,正如其他人在注释中提到的,您应该使用fgets()而不是gets(),没有办法安全地使用后者。如果您想知道如何将其用于用户输入,请参见this answer。
这应该表明gets()被认为是多么糟糕,它实际上已经被废弃并从标准中删除了。
https://stackoverflow.com/questions/72750404
复制相似问题