通过 atoi 转换的复制字符串交付 0

标签 c

如果准备就绪,此工具应该可以计算出一个人的年龄。它获取系统日期并询问用户生日。然后通过将重要字符复制到新字符串中,将输入的字符串拆分为“年”(bjahr)、“月”(bmonat) 和“日”(btag)。在此之后,它通过 atoi 将它们转换为 int 值。

为了检查是否一切正常,我打印了它。但是问题开始了。这一年工作正常,但“intmonat”和“inttag”似乎为 0。 我找不到错误,你能帮我吗?

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
#include <string.h>

int main ()
{
    SYSTEMTIME time;
    GetSystemTime (&time);

char name[20], bday[10], bjahr[4], bmonat[2], btag[2]; 

int year = time.wYear;
int month = time.wMonth;
int day = time.wDay;
int intjahr, intmonat, inttag;

printf("\n\n today is the: %i.%i.%i \n\n",day,month,year);
printf(" please insert Birthdate (dd.mm.jjjj).\n\n");

gets(bday);

strncpy(bjahr , &bday[6], 5);
strncpy(btag  , &bday[0], 1);
strncpy(bmonat, &bday[3], 1);

intjahr  = atoi(bjahr) ;
intmonat = atoi(bmonat);
inttag   = atoi(btag)  ;

printf("\n\n jahr %i \n\n",intjahr);
printf(" monat %i \n\n",intmonat);
printf(" tag %i \n\n",inttag);        

system("PAUSE");

}

我是德国人,这就是为什么有些词可能不是英语希望这没关系。

最佳答案

您的变量太短:例如,您希望月份有两个字符,但您还需要考虑终止字符串的 \0。此外,您只是每天和每月复制一个字符,而不是 null 终止它。所以应该是:

char name[20], bday[11], bjahr[5], bmonat[3], btag[3];

...

gets(bday);

strncpy(bjahr , &bday[6], 4);
bjahr[4] = 0;
strncpy(btag  , &bday[0], 2);
btag[2] = 0;
strncpy(bmonat, &bday[3], 2);
bday[2] = 0;

但更好的解决方案是改用 scanf,您应该阅读并熟悉它。例如,它可以轻松帮助您正确解析像 1.2.2000 这样的输入。

此外,您当前使用固定大小数组的解决方案很容易产生缓冲区溢出(只需输入 abcdefghijklmnopqrst)。你应该这样做:

fgets(bday, sizeof(bday), stdin);

关于通过 atoi 转换的复制字符串交付 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7088818/

相关文章:

c - 未命中 launch.json 断点中添加的命令行参数时的 visual studio 代码

c - 变量声明和定义不匹配

c - 使 fscanf 忽略可选参数

相当于 fork 的克隆?

c - C中指向特定地址的指针

c++ - 将 FFMPEG 帧写入 png/jpeg 文件

c - 如果文件大小不变, fopen 更新模式 ("rb+") 是否会更改文件的磁盘位置?

c - 每行从文本文件中打印 x 个字节,直到 EOF

c - 使用 C 中的 openssl 库进行简单的 AES 加密解密

c++ - 为什么通过 ***char 传递给函数的 nullptr 终止数组会丢失终止元素?