Link to home
Start Free TrialLog in
Avatar of effectivista
effectivista

asked on

working with string in c

my code is like

char rollno[5];
char name[20];
char mesg[]="12345expert"
int k;
k= strlen(mesg);
strncpy(rollno,mesg,5);
strncpy(name,mesg+5,k);
printf("%s",rollno);
printf("%s",name);

and gives output like
12345@23A343
expert

why i don't  know . but it works well in another program.
pls help  i m
getting here unnecessary chars with rollno

dhiraj
ASKER CERTIFIED SOLUTION
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You need:

char rollno[6]; // 5 is not enough for 5 characters and a terminator.
char name[20];
char mesg[]="12345expert"
int k;
k= strlen(mesg);
strncpy(rollno,mesg,5);
strcpy(name,mesg+5); // Just copy the rest.
printf("%s",rollno);
printf("%s",name);

You should now get
"12345expert"

which may still confuse you until you change it to:

printf("%s\n",rollno);
printf("%s\n",name);

Paul
which is basically what I said...

Does

    strncpy(rollno,mesg,5);

add the \0 in then?  I didn't realise that...
ahhh, I see, you could be relying on the rollno char arry being initialized to all \0s
strncpy will NOT append a '\0' if it copied the specified number of characters.

What asker probably should have done was:

char rollno[6]; // 5 is not enough for 5 characters and a terminator.
char name[20];
char mesg[]="12345expert"
sscanf ( mesg, "%5s%s", rollno, name );
printf("%s\n",rollno);
printf("%s\n",name);

But I was trying to fix the code, not rewrite it.

Paul
>>ahhh, I see, you could be relying on the rollno char arry being initialized to all \0s
But that's a good point too, so the code SHOULD have been:

char rollno[6]; // 5 is not enough for 5 characters and a terminator.
char name[20];
char mesg[]="12345expert"
int k;
k= strlen(mesg);
strncpy(rollno,mesg,5);
rollno[5] = '\0'; // Just in case.
strcpy(name,mesg+5); // Just copy the rest.

but I stand by my suggestion that sscanf would be a better tool here.

Paul
>> so the code SHOULD have been:

Which again is what I said...
Tim,

I offer a complete and utter retraction. The imputation was totally without basis in fact and was in no way fair comment and was motivated purely by malice, and I deeply regret any distress that my comments may have caused you or your family, and I hereby undertake not to repeat any such slander at any time in the future.

Paul