2012-07-25 26 views
-1

我的程序中有什么错误?这是代码:为什么变量在程序的一部分中正确打印,但不是另一部分

/* 
* courseProject.c 
* 
* It is a simple database for record shop 
* to track its iventory of CDs 
* 
* by Mahmoud Emam, 2012. 
*/ 
#include<stdio.h> 

main() 
{ 
     /* 
     * CDs infrormations 
     */ 
     char title[31], artist[31]; 
     short int numberOfTracks; /* short to save memory */ 
     int albumOrSingle;   /* Boolean to check 1 for Album and 0 for Single */ 
     float price; 

     printf("Hello, Welcome to Record Shop!\n\n"); 
     /* 
     * Asking for CD details 
     */ 
     printf("Enter CD details\n\n"); 
     printf("CD's Title: "); 
     scanf("%[^\n]", title); 
     fflush(stdin); 

     printf("CD's Artist: "); 
     scanf("%[^\n]", artist); 


     printf("Number of tracks: "); 
     scanf("%d", &numberOfTracks); 


     printf("Please press \"1\" for album, \"0\" for single: "); 
     scanf("%d", &albumOrSingle); 


     printf("CD's Price: "); 
     scanf("%f", &price); 

     /* 
     * Output CD details 
     */ 
     printf("\nCD details:\n"); 
     printf("=============\n\n"); 

     printf("CD's Title: <%s>\n", title); 
     printf("CD's Artist: <%s>\n", artist); 
     printf("Number of tracks: <%d>\n", numberOfTracks); 

     if (albumOrSingle) 
     printf("This is <Album>\n"); 
     else 
     printf("This is <Single CD>\n"); 

     printf("Its price = <%.2f>\n", price); 
     printf("=============\n\n"); 

     /* Exit from program */ 
     printf("Press any key to exit\n"); 

     fflush(stdin); 
     getchar(); 
} 

这是一个简单的程序,它从用户读取CD信息并在屏幕上再次输出详细信息。但是,artist变量始终为空。为什么?

我从用户那里读取并制作了printf("%s", artist);,它工作正常,但它在程序结束时不起作用。变量总是空的。

+0

可能对[codereview.SE](http://codereview.stackexchange.com)更好,这不是为我的网站找到问题。 – 2012-07-25 16:40:12

+0

谢谢:)寻求帮助 – 2012-07-25 16:41:35

+3

不是'fflush(stdin);'UB? – 2012-07-25 16:41:53

回答

2

变量numberOfTracksshort int,但你与scanf%d符,用于读取int阅读它。这会导致未定义的行为 - 在这种情况下,它可能会覆盖其他变量,例如artist

请使用%hd说明符(其读取short int),或将变量更改为int

+0

但** numberOfTrackes **存储正确 – 2012-07-25 17:20:02

+0

它可能正确存储在您的特定机器上,但不能保证始终如此。这是未定义行为的本质。即使在你的机器上,它显然会覆盖其他变量。 – interjay 2012-07-25 17:22:24

+0

谢谢:) @interjay C在开始时很难:) 这是第一个程序 – 2012-07-25 17:25:45

0

那么,numberOfTracks是一个简短的,你正在做一个scanf(“%d”,& numberOfTracks)这将有有趣的结果。

另外,main是int main(),你应该返回一个值。此代码的可能结果是,您的程序将以随机值终止,而该值恰好与用户的按键密切相关。

相关问题