c - 如何确保 fgets 准确接受带前导 0 的数字?

标签 c

我正在尝试创建一个程序,该程序本质上接受用户输入并将其乘以 12 并输出该数字。尽管我遇到了下面的问题,但我已经把它记下来了。

expected output :   
./test  
minutes: 0000004  
bottles: 48  

actual output :  
$ ./test  
minutes: 0000004  
minutes: minutes: bottles: 48  

我想解决这个问题,而不必将 分钟Str[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;

这也是我的第一个问题,所以如果我做错了什么,请告诉我。

最佳答案

试试这个

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));

关于c - 如何确保 fgets 准确接受带前导 0 的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37181356/

相关文章:

c++ - 加权有向图中从节点返回自身的最短距离

c - 使用 malloc 的多个数组

c - 如何获取gcc编译后执行的文件名?

C代码通过Linux中的蓝牙串行端口配置文件从nonin脉搏血氧计设备读取数据

c - 当我在 IF 体内声明变量时有什么缺点吗?

c - 如何修复 c 中对 '_imp_curl_easy_setopt' 的 undefined reference ?

c - 从c中的文件中读取所有字节

c - 从左到右评估

c - 使用指针访问二维数组会出现错误

c - 使用 gethostbyname