开发者

Why doesn't this tool print the strings?

this tool is for me to learn how to work with strings. but if it finished, sometimes, it should compare two dates (the systemdate and a entered birthday date) and tell the user how old the person is. but i get stuck. i wanted to try some basics at first, so the entered string ge开发者_StackOverflow中文版ts split into day month and year and then it should print the strings. But my real aim is, to convert them to an int value so that i can calculate with them.

But for some reasons the tool don't print the entered string, it just print 3 \n and i can't figure out the problem.

please help.

edit: fixed it again almost ready only the "btag" makes some some trouble. "bmonat" and "bjahr" works fine now thank u so far!

/*age check (c) By Tim Hartmann*/


#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[3], btag[3]; 

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], 4);
    bjahr[4] =  '\0';

strncpy(bmonat, &bday[3], 2);
    bmonat[2]=  '\0';        

strncpy(btag  , &bday[0], 2); /* here is the probleme */
    btag[2]  =  '\0'; 

printf("\n %s \n",   bjahr);
printf("\n %s \n",  bmonat);
printf("\n %s \n",    btag);

system("PAUSE");

 }


There are a few things wrong with this. For starters, bjahr[4] = 0; bmonat[2]= 0; btag[2] = 0;

These are all trying to access things outside your size limitations on your buffer.

Another thing is that you are probably want

bjahr[4] =  '\0';
bmonat[2]=  '\0';
btag[2]  =  '\0';

Instead, as this gives you null characters instead of 0's.


The strings you declare (bday, bjahr, bmonat, btag) lack 1 char to store the \0

btag for instance should be btag[3], particularly since you are doing btag[2] = 0 later in the source

Can you try adding 1 more char to all your strings and check if it corrects everything?


It should look like this:

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

if you want 20 chars max for the name, 10 for the bday, ...

then, when extracting the date:

strncpy(btag, &bday[0], 2);
    btag[2] = '\0';

This way, you copy 2 chars from bday in btag (starting at offset 0) and then you set the 3rd char to '\0' to end the string

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜