我正在尝试创建一个程序,它基本上接受用户输入并将其乘以12并输出该数字。我已经解决了这个问题,尽管我遇到了下面的问题。
expected output :
./test
minutes: 0000004
bottles: 48
actual output :
$ ./test
minutes: 0000004
minutes: minutes: bottles: 48
我想解决这个问题而不必将minutesStr [4]更改为更大的数字。我想要的一个想法是更改我的缓冲区以存储值,将前导0关闭,并将其从缓冲区中取出。我也经过研究,我发现scanf可以解决领先的0问题,但我想在不使用scanf的情况下这样做,因为它是"坏"。我也只是想学习。
// Set buffer size to 0 to fix printf/fgets problem
setvbuf(stdout, 0, _IONBF, 0);
char minutesStr[4]; // This limits minutes to < 999
char *end;
int minutes = 0;
int i = 0;
int offset;
do
{
printf("minutes: ");
// Takes in user input string, sizeof(string), from keyboard
fgets(minutesStr, sizeof(minutesStr), stdin);
while (minutesStr[i] == '0')
{
i++;
}
if (minutesStr[i] == '\n')
for ( offset = 0; offset < i; offset++ )
{
minutesStr[offset] = minutesStr[offset + i];
}
// returms size of string up to \n and replaces it with null terminator
minutesStr[strlen(minutesStr) - 1] = '\0';
// minutes = (Convert the string into a long)
minutes = strtol (minutesStr, &end, 10);
}
while ( minutes < 1 );
printf("bottles: %d\n", (minutes * 12));
return 0;
这也是我的第一个问题,如果我做错了,请告诉我。
答案 0 :(得分:0)
试试这个
char minutesStr[4]; // This limits minutes to < 999
int minutes = 0;
int i = 0;
do {
printf("minutes: ");
do{
fgets(minutesStr, sizeof(minutesStr), stdin);
for(i = 0; minutesStr[i] == '0'; ++i)
;
} while(i == sizeof(minutesStr) -1);
if(i != 0 && !strchr(minutesStr, '\n')){
int len = sizeof(minutesStr) - i -1;
memmove(minutesStr, minutesStr + i, len);
fgets(minutesStr + len, sizeof(minutesStr) - len, stdin);
}
minutes = strtol (minutesStr, NULL, 10);
} while ( minutes < 1);
printf("bottles: %d\n", (minutes * 12));
答案 1 :(得分:0)
使用fgets()
和然后解析。
将用户输入与输入解析分开。 @DevSolar
char buf[100];
fgets(buf, sizeof buf, stdin);
int n = 0;
sscanf(buf, "%*[0-9]%n", &n);
// If input is only made up of 6 digits and line feed
if (n == 6 && buf[n] == '\n') {
// Success
int minute = atoi(buf);
} else {
; // Fail
}