473,609 Members | 1,943 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Strcpy versus Strncpy in arrays

SK
Hi
I appreciate all of the feedback I have recieved. I am enjoying
working on my program and I hope that it can be appreciated. I have my
program compiling now and I am continuing to work out the bugs. I have
two problems that I cannot seem to resolve:

1. I want to have someone enter in as many employees as they want
to..and for each employee entered I would like to save the data from
that entry to print out at the end of the program. I continue to run
into a problem with the loop. I actually did not intend to use arrays
however I cannot seem to figure outany other way to approach the
problem.

2.This second problem is probably due to using arrays
intheprogram,ho wever that being said I still want to figure this
out....I am trying to connect two strings together, concatenation. I
understandthat strncpy refers to n number of characters versus strcpy
is the actual character but the difficulty I am running into has to do
with the syntax. It is evident that I am somehow not correctly dealing
with putting things into memory and then extracting them. Any
thoughts??

//Specs to be added later

//C Libraries
#include <stdio.h>
#include <math.h>
#include <string.h>
//Global Constants
# define FULLNAME 20
# define EMPLOYEES 1000
//Global Defined Constant
const float OT = 1.5;

//Global Variable Declaratives
FILE*inp;

//Global Constants
# define FULLNAME 20
# define EMPLOYEES 1000

char fn[FULLNAME];
char ln[FULLNAME];
char department[20];
char again;
int count_EMP;
int number_EMP;

float wage;
float OTwage;
float hours;
float RegHr;
float RegHrPay;
float OTHrPay;
float OTHr;
float GrossPay;


int main(void)
{
/*Define the structure.*/
struct EMP_WeeklyPay
{
char first_name[FULLNAME];
char last_name[FULLNAME];
float RegHr;
float wage;
float OTHr;
float OTHrPay;
float GrossPay;
};
/*Rename the structure syntax.*/
typedef struct EMP_WeeklyPay EWP;
/*Create an array of structures.*/
EWP emp[EMPLOYEES];

/*Counters*/
int n, numemp;
int count = 0;

printf("\n\nMou ntain Pacific Corporation\n") ;
printf("Departm ent Salary Program\n\n");
printf("Please enter the name of the department: ");
scanf("%s", department);
/*Loop to read in employee wage data*/
count_EMP = 0;
count_EMP++;

for (n = 0; n < EMPLOYEES; ++n){
do{
printf("\nEnter employee # %d: ", count_EMP);
scanf("%s %s", &fn, &ln);

printf("\nPleas e enter the hourly wage for the employee:
");
scanf("%f", &wage);

printf("\nPleas e enter the number of hours worked this"
" week: ");
scanf("%f", &hours);

printf("\nThank you. Process another employee?");
scanf("%s", &again);

}while(again == 'Y' || again == 'y');

/*Read in the input*/

numemp = scanf("%11s%11s %f%f%f%f%f", &fn, &ln, &RegHr,
&wage, &OTHr, &OTHrPay, &GrossPay);

/*Check if user is done*/


if(again != 'Y' && again !='y');
printf("End of processing\n\n\ n");
/*Process the input*/
if(numemp == 6)
{

if (RegHr > 40)
{
OTHr = hours - 40;
OTHrPay = OT * OTHr * wage;
RegHrPay = 40.0 * wage;
}

else
{
RegHrPay = hours * wage;
OTHrPay = 0.0;

}

GrossPay = RegHrPay + OTHrPay;

strncpy(emp[n].first_name, fn, FULLNAME);
emp[n].first_name[FULLNAME] = '\0';

strncpy(emp[n].last_name, ln, FULLNAME-1);
emp[n].last_name[FULLNAME-1] = '\0';

emp[n].RegHr = RegHr;
emp[n].wage = wage;
emp[n].OTHr = OTHr;
emp[n].OTHrPay = OTHrPay;
emp[n].GrossPay = GrossPay;
++count;
}

/*Print Table*/

printf("\n\nMou ntain Pacific Corporation\n") ;
printf("Departm ent Salary Program\n\n");

printf("Employe e Reg Hrs "
"Overtime Hrs Gross\n");

printf("-----------------------------------------"
"-------------------------\n\n");


for(n=0; n < count; ++n) {
printf("%-35s%-17s%12f%10f%12f %10f%%5f",
emp[n].first_name,
emp[n].last_name, emp[n].RegHr,
emp[n].wage, emp[n].OTHr, emp[n].OTHrPay,
emp[n].GrossPay);
}
}
}

Nov 15 '05 #1
53 4262
SK wrote:
2.This second problem is probably due to using arrays
intheprogram,ho wever that being said I still want to figure this
out....I am trying to connect two strings together, concatenation. I
understandthat strncpy refers to n number of characters versus strcpy
is the actual character but the difficulty I am running into has to do
with the syntax. It is evident that I am somehow not correctly dealing
with putting things into memory and then extracting them. Any
thoughts??


Stop working on your program here and start another one just for testing
out how strcpy and strncpy work. Also, read the documentation of both
functions. If you have problems with some very specific thing, post a
minimal example - your growing main project doesn't qualify as minimal
example.

Lastly, in order to handle arbitrary strings, you will need
malloc/realloc/free for the memory handling and strlen, strcpy and strcat
for the string operations. The *n* variants are usually only necessary if
you operate on fixed size arrays, for dynamic strings you better resize
them beforehand.

Uli

Nov 15 '05 #2
On 13 Nov 2005 12:04:08 -0800, in comp.lang.c , "SK"
<ba******@aol.c om> wrote:

//Global Defined Constant
const float OT = 1.5;
You really don't want to use float - use double.
scanf("%s", department);
As I said before, scanf is a bad function to use for this. Consider
what happens if someone enters 22 characters.
for (n = 0; n < EMPLOYEES; ++n){
usual to do n++
do{
printf("\nEnter employee # %d: ", count_EMP);
scanf("%s %s", &fn, &ln);
fn and ln are not defined. Assuming they're supposed to be strings,
you don't need the ampersands.
scanf("%s", &again);

}while(again == 'Y' || again == 'y');
again is a string, not a single char so you need "Y" and "y". Or
better yet, declare again as a character and use the %c format.

/*Read in the input*/
you never asked the user to enter any...
numemp = scanf("%11s%11s %f%f%f%f%f", &fn, &ln, &RegHr,
&wage, &OTHr, &OTHrPay, &GrossPay);


again, fn and ln don't seem to be defined.
You also seem to have some big problems with loops.

Take a step back. Write down _in english_ (or your native language), a
description of what the programme has to do. Consider carefully how
each piece of data needs to be obtained and stored.

Then, once you have a design, start writing code.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 15 '05 #3
Mark McIntyre wrote:
fn and ln are not defined.


He's got a bunch of globals, and those are two of them.
scanf("%s", &again);

}while(again == 'Y' || again == 'y');


again is a string, not a single char so you need "Y" and "y". Or
better yet, declare again as a character and use the %c format.


'again' was declared as a char. another global

--
pete
Nov 15 '05 #4
Mark McIntyre wrote:
On 13 Nov 2005 12:04:08 -0800, in comp.lang.c , "SK"
<ba******@aol.c om> wrote:

for (n = 0; n < EMPLOYEES; ++n){


usual to do n++

Ummm, what? Usual for whom? K&R uses the prefix notation. It's so
common as to be completely unremarkable.

Brian
Nov 15 '05 #5
On 14 Nov 2005 19:40:25 GMT, in comp.lang.c , "Default User"
<de***********@ yahoo.com> wrote:
Mark McIntyre wrote:
On 13 Nov 2005 12:04:08 -0800, in comp.lang.c , "SK"
<ba******@aol.c om> wrote:

> for (n = 0; n < EMPLOYEES; ++n){


usual to do n++

Ummm, what? Usual for whom?


Not for whom, for what.

int array[10];

for(i=0;i<10;++ i)
array[i] = i;

In this context particularly, I find pre-increment especially
counterintuitiv e.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 15 '05 #6
On Sun, 13 Nov 2005 23:57:55 GMT, in comp.lang.c , pete
<pf*****@mindsp ring.com> wrote:
Mark McIntyre wrote:
fn and ln are not defined.


He's got a bunch of globals, and those are two of them.


not in the version I was commenting on - I checked.
again is a string, not a single char so you need "Y" and "y". Or
better yet, declare again as a character and use the %c format.


'again' was declared as a char. another global


Not in the verison I was commenting on - it was a character array.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 15 '05 #7
Mark McIntyre <ma**********@s pamcop.net> writes:
On 14 Nov 2005 19:40:25 GMT, in comp.lang.c , "Default User"
<de***********@ yahoo.com> wrote:
Mark McIntyre wrote:
On 13 Nov 2005 12:04:08 -0800, in comp.lang.c , "SK"
<ba******@aol.c om> wrote:

> for (n = 0; n < EMPLOYEES; ++n){

usual to do n++

Ummm, what? Usual for whom?


Not for whom, for what.

int array[10];

for(i=0;i<10;++ i)
array[i] = i;

In this context particularly, I find pre-increment especially
counterintuitiv e.


I agree with "Default User". I suppose I have a slight preference for
postincrement, but I don't find either one counterintuitiv e or
jarring, and my guess is that most other C programmers feel the same
way. And of course they're completely equivalent in that context (as
they are in statement context). I hardly even notice which one is
used; I think I mentally translate both to "increment i" if the result
isn't used.

But then we all have our little quirks, like my own strong distaste
for "42 == x" rather than "x == 42" (and yes, I know the arguments).
So I won't criticize you for disliking ++i, but you should be aware
that your dislike is (probably) a minority viewpoint.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #8
On 2005-11-14, Mark McIntyre <ma**********@s pamcop.net> wrote:
On 14 Nov 2005 19:40:25 GMT, in comp.lang.c , "Default User"
<de***********@ yahoo.com> wrote:
Mark McIntyre wrote:
On 13 Nov 2005 12:04:08 -0800, in comp.lang.c , "SK"
<ba******@aol.c om> wrote:

> for (n = 0; n < EMPLOYEES; ++n){

usual to do n++

Ummm, what? Usual for whom?


Not for whom, for what.

int array[10];

for(i=0;i<10;++ i) array[i] = i;

In this context particularly, I find pre-increment especially
counterintuitiv e.


Why? The final result [i.e. what ++i evaluates to] is what is tested
for being less than 10. I tihnk the real issue is that it's not what
you're used to.
Nov 15 '05 #9
Keith Thompson wrote:
Mark McIntyre <ma**********@s pamcop.net> writes:
On 14 Nov 2005 19:40:25 GMT, in comp.lang.c , "Default User"
<de***********@ yahoo.com> wrote:
Mark McIntyre wrote:

On 13 Nov 2005 12:04:08 -0800, in comp.lang.c , "SK"
<ba******@aol.c om> wrote:

> for (n = 0; n < EMPLOYEES; ++n){

usual to do n++
Ummm, what? Usual for whom?
Not for whom, for what.

int array[10];

for(i=0;i<10;++ i)
array[i] = i;

In this context particularly, I find pre-increment especially
counterintuitiv e.


I agree with "Default User". I suppose I have a slight preference for
postincrement, but I don't find either one counterintuitiv e or
jarring, and my guess is that most other C programmers feel the same
way. And of course they're completely equivalent in that context (as
they are in statement context). I hardly even notice which one is
used; I think I mentally translate both to "increment i" if the result
isn't used.


Right. I personally use i++ most of the time, but find ++i so
unremarkable that I, well, don't remark upon it. I would expect that
most compilers would render the same machine code for either in that
context.

As I said, K&R 2 uses preincrement. Someone pointed that out to me some
time back, which surprised me. I literally had never noticed that they
didn't use postincrement, and would have sworn that they did.
But then we all have our little quirks, like my own strong distaste
for "42 == x" rather than "x == 42" (and yes, I know the arguments).
I agree with you. I don't like it, so I don't use it.
So I won't criticize you for disliking ++i, but you should be aware
that your dislike is (probably) a minority viewpoint.


I don't even know that preference for i++ is a minority opinion, but
most likely CARING would be a minority opinion.


Brian

Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
489
by: Paul Sheer | last post by:
I need to automatically search and replace all fixed size buffer strcpy's with strncpy's (or better yet, strlcpy's) as a security and stability audit. The code base is large and it is not feasable to manually perform these changes. I would like perhaps a C++ parser that can automatically detect use of a strcpy to a buffer of fixed size. For instance, struct x { char member;
9
12777
by: Pascal Damian | last post by:
I read somewhere that strcpy() is safer when dealing with malloc()-ed strings. Is that true? (Of course I know that both are unsafe). -- Pascal
81
7276
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there be any advantage in having strcat and strcpy return a pointer to the "end" of the destination string rather than returning a
302
18447
by: Lee | last post by:
Hi Whenever I use the gets() function, the gnu c compiler gives a warning that it is dangerous to use gets(). Is this due to the possibility of array overflow? Is it correct that the program flow can be altered by giving some specific calculated inputs to gets()? How could anyone do so once the executable binary have been generated? I have heard many of the security problems and other bugs are due to array overflows.
38
2697
by: edu.mvk | last post by:
Hi I am using strcpy() in my code for copying a string to another string. i am using static char arrays. for the first time it is exected correctly but the second time the control reaches then the SEGMENTATION FAULT is occuring. Please tell me what are all the cases this problem may occur if we use strcpy().
4
9530
by: chikito.chikito | last post by:
1. Can someone tell me the difference between these two functions: void strcpy(char *s1, const char *s2) { while(*s1++ = *s2++) ; } //function prototype of strcpy follows char *strcpy(char *s1, const char *s2) // library function
0
8145
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8095
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8236
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8410
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7030
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6068
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4103
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1690
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1407
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.