Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strncpy and strcat usage

Tags:

c

syntax

string

My homework requires that my name be displayed such that it looks like this: 'Lastname, Firstname'. Last name then [comma space] firstname. While not moving over the rest of the text after that name. This is my code:

  char str1[11];
  char str2[3];
  char str3[16];
  strcpy (str1,fn);
  strcpy (str2,", ");
  strcpy (str3,ln);
  strncat (str1, str2, 14);
  strncat (str1, str3, 31);

My teacher said that I did what he wanted, but he doesn't like how many lines of code I used and said I am doing extra work than I need.

Variables: ln = last name, fn = first name I made str2 for the ', ' comma space.

What is it that he wants me to do?

like image 640
GeekyDewd Avatar asked Dec 06 '22 19:12

GeekyDewd


2 Answers

Assuming you know length of strings, why not do

char result[50];

sprintf(result,"%s, %s",ln, fn);
like image 178
aggaton Avatar answered Dec 27 '22 12:12

aggaton


char result[50];

strcpy(result, ln);
strcat(result, ", ");
strcat(result, fn);

He's right, you used way too many statements (and wasted too much memory doing it).

like image 29
Blindy Avatar answered Dec 27 '22 11:12

Blindy