我真的被这个难住了。
我在 c 中编写了一个简单的程序,用于从用户键盘输入中检索名字、姓氏和 YOB(出生年份)(我还没有时间将年龄解析为整数)并且我设置了最大字符数为输入。
但是,每当我允许字段的最大字符数为 50 或更大时,返回值始终为空白。
这是代码(60 行),输出如下。引起问题的函数是倒数第二个函数getInputNoNewLine:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void flushBuffer();
char *getInput(int max, char message[]);
char *getInputNoNewline(int max, char message[]);
typedef struct Person {
char *firstName;
char *lastName;
int yob;
} Person;
void flushBuffer() {
int ch;
while ((ch = getchar()) != '\n' && ch != EOF); //flush the input buffer
}
char *getInput(int max, char message[]) {
char in[max];
char *input;
do {
printf("%s", message);
input = fgets(in, max + 2, stdin); //max + 2 accounts for characters fgets adds
if (input[strlen(input)-1] != '\n') {
printf("Sorry, maximum %d characters\n", (max));
flushBuffer();
}
} while (input[(strlen(input)-1)] != '\n');
printf("input: %s", input); //debug
return input;
}
//OFFENDING FUNCTION
char *getInputNoNewline(int max, char message[]) {
char *input;
input = getInput(max, message);
printf("raw input : %s", input); //debug
if (input[strlen(input) - 1] == '\n') { //strip new line character
input[strlen(input) - 1] = '\0';
}
printf("final input: '%s'\n", input); //debug
return input;
}
int main(int argc, char *argv[]) {
int numPlayers = 3;
char *intIn;
int i = 0;
Person players[numPlayers];
printf("Hello world Game\n");
for (i = 0; i < numPlayers; ++i) {
players[i].firstName = getInputNoNewline(50, "What is your first name: "); //50 will return blank
players[i].lastName = getInputNoNewline(49, "What is your last name: "); //49 will return fine
intIn = getInputNoNewline(4, "What is your YOB: "); //TODO: convert number to integer with sscanf
printf("-----------------------------------\n");
}
printf("Finished\n");
return 0;
}
这是输出,您可以看到 jim 的第一个输入是从 fgets 接收的,但返回值为空白(原始输入:)。如果我要将最大值从 50 减少到 49,根据姓氏字段的情况,它工作得很好。有什么想法吗?
Hello world Game
What is your first name: jim
input: jim
raw input : final input: ''
What is your last name: smith
input: smith
raw input : smith
final input: 'smith'
What is your YOB: 1984
input: 1984
raw input : 1984
final input: '1984'
-----------------------------------