使用fgets()获取输入;并保存不同于输入

时间:2015-04-15 21:56:05

标签: c unix

我正在拍摄2个程序并将它们连接起来完成家庭作业,它会询问用户输入,并保存与输入不同的值。程序1中的代码是教授的,而不是用于调试的打印语句,而其他代码则没有任何问题。但我很好奇为什么它没有正确保存。

计划1:

#include        <stdlib.h>
#include        <stdio.h>

#define         TEXT_LEN        256


//
//      Declarations go here:
//

//  PURPOSE:  To hold the computer's answer.
extern int      answer;

//  PURPOSE:  To, in a loop:
//      (1) get an integer that from the user by calling 'getGuess()',
//      (2) increment 'count',
//      (3) compare the user's guess with 'answer'
//        (3a) if they are equal, print how may guesses the user used and
//             quit the loop,
//        (3b) if the guess too high print print "Too high!\n"
//        (3c) if the guess too low print print "Too low!\n"
//      No parameters.  No return value.
extern
void            playGame        ();


//
//      Function and variables go here:
//

//  PURPOSE:  To keep track of the number of guesses the user used.
int             count   = 0;


//  PURPOSE:  To set 'answer' to the computer's answer.  No parameters.  No
//      return value.
void            generateAnswer  ()
{
  answer        = rand() % 256;
  printf("answer: %d",answer);
}
//  PURPOSE:  To ask the user for an integer, and to return it.  No parameters.
int     getGuess    ()
{
  char  numberText[TEXT_LEN];

  printf("Please guess my number in 0..255: ");
  fgets(numberText,TEXT_LEN,stdin);
  return(strtol(numberText,NULL,10));
}


 int    main    ()
{
  generateAnswer();
  playGame();
  return(EXIT_SUCCESS);
}

计划2:

#include <stdlib.h>
#include <stdio.h>
#define         TEXT_LEN        256

int answer;
int count;
void playGame();
int numberText;

void playGame()
{
 printf("user input: %d",numberText);
 getGuess();
 if( answer > numberText)
 {
  printf("Too Low!");
  count += 1;
 }
 if( answer < numberText)
 {
  printf("Too High!");
  count += 1;
 }
 if (answer == numberText)
 {
  count += 1;
  printf("Just right! It took %d tries",count);
  return;
 }
 playGame();
}

输出:

[tplutz@cdmlinux CSC374]$ ./whole
    answer: 103user input: 0Please guess my number in 0..255: 23
    user input : -1078133976 Too Low!user input: 0Please guess my number in     0..255: 150
    user input : -1078133992 Too Low!user input: 0Please guess my number in 0..255: 103
    user input : -1078134008 Too Low!user input: 0Please guess my number in 0..255:`

1 个答案:

答案 0 :(得分:1)

没有作业

getGuess();
if( answer > numberText)

应该是

answer = getGuess();
if( answer > numberText)

从评论中找到答案并转移到社区,因此OP可以关闭它。

信用:@John Bollinger @BLUEPIXY