Aia 1,977 Nearly a Posting Maven

That's the behavior coded in your snippet.
A possible solution is to use a template like this.

int main(void)
{
    /* your code here */

    getchar(); /* wait until you press a key */
    return 0;
}
Aia 1,977 Nearly a Posting Maven
awk '{split($0, a, ","); sub(/\)/,"",a[3]); print a[3]}' source.file > result.file

Or

sed 's!( [0-9],[0-9],\([0-9]\) )!\1!' source.file > result.file
Aia 1,977 Nearly a Posting Maven

It is all about clarity, and as with everything where you must choose, there are advantages and disadvantages among them. You will grow a preference eventually. Nevertheless, it is considerate good programming practice to be consistent in the style when you code. Especially, when you do not have the luxury of applying your preference, e.i. company practices, group project, or code maintenance, written by others.

Aia 1,977 Nearly a Posting Maven

No I am a beginner to c and it was suggested that I use this one.

Thought so.
Stay away from whatever source "suggested" it.
There are a few good recommendations for compilers (free of charge) in that "facts" link I posted previously.

Aia 1,977 Nearly a Posting Maven

Is there any particular reason why you want to use such compiler?

Explicit facts

Aia 1,977 Nearly a Posting Maven
#! /bin/bash
# read each name and pass it to grep to create a different identity file log
while read name
do
# any line in yyy.csv that contains $name is gathered and sent to $name.csv
grep $name yyy.csv > $name.csv
done < userlist

Just another quick question on this. If I want to read from the file yyy.csv if it is in another directory what syntax should I use?
If it was in terminal I would only need to go down one level (i.e. use cd ..) to get to the directory I want to use.
Any ideas?

Thanks,

N

Same thing. You can use an absolute path e.i. /home/niall_heavey/logfiles/yyy.csv or you can pass it a relative path e.i ../yyy.csv

Aia 1,977 Nearly a Posting Maven

niall_heavey> Would this be preferable as a csv file or should I use something else like txt or other?
An ASCII text file is the simplest

niall_heavey> Also, if there was two columns in this would it cause trouble?
Nope, grep looks for the term and if finds it, will send the whole line to the output of choice, in this case a file with the username

niall_heavey> Also, which would be best? The bash or shell? Or is there much of a difference?
Bash is the default shell for Ubuntu. There are many shells, Bash it one of the most popular.

niall_heavey> And finally, in both codes you use "name" do I use it as you have it or is it to signify something?
name is just a variable identifier, it is not a built-in keyword. You can use any identifier than makes sense to you, as long as it starts with an alphanumeric or underscore character
Don't forget the $ symbol in front when dereferencing it.

Aia 1,977 Nearly a Posting Maven

niall_heavey> Hope this all makes sense!
Some but not all, since it is missing information

I'll work with what you gave me. I'll explain.
You mentioned the first 50 users.

You must have, then, a way to identify those users. Assuming a file list with each user name in each line, we will call that file userlist
Now we can start working

#! /bin/bash

# read each name and pass it to grep to create a different identity file log
while read name
do
    # any line in yyy.csv that contains $name is gathered and sent to $name.csv
    grep $name yyy.csv > $name.csv
done < userlist

or

#! /bin/bash

for name in $(cat userlist)
do
    grep $name yyy.csv > $name.csv
done
Aia 1,977 Nearly a Posting Maven

can u tell me why u use cUser[5][10]
why not *cUser[5]
what is the advantage to use the cUser[5][10]????????????

One of the best methods to turn people off from helping you in a high tech forum is to write like a "valley-girl-teenager" in a phone text messaging session. Avoid the sticky-key syndrome and use correct English.
After that, you exercise patience.

Aia 1,977 Nearly a Posting Maven

How I'm calling the function:

pay_ending_date

I don't understand why it works when run directly from the script but doesn't work when embedded inside a function?

The call is missing the parameter

pay_ending_date $1

or

pay_ending_date "filename"
Aia 1,977 Nearly a Posting Maven

Well for 1 they tend to make your application slower & inefficient. It's like using your furniture to produce heat, or calling a bull-dozer to open your front door.
The events taking place upon calling system() are roughly the foll:
1. Suspends your program.
2. Calls the OS Shell. (Slowest Step)
3. OS Shell finds the command.
4. Allocates memory to execute it.
5. Executes it.
6. Deallocates memory
7. Exits the shell.
8. Resumes your program.

For 2, take the following example under Windows Environment:

system("dir");

Suppose the end-user has an executable dir.exe in the current directory, so instead of executing the "dir" command on the shell, the program opens/executes "dir.exe", which under extreme conditions might even be a file-deleting virus!
Pretty much, if it's available as a shell command, it can be done in C++.

When you do not mention the original source, it is called plagiarism if you make it to look like it came from you.
http://www.gidnetwork.com/b-61.html

Aia 1,977 Nearly a Posting Maven

Why should system calls be avoided if you know your target environment ?

Because it is expensive. It is like taking a "Boeing 747" to go for groceries to the local supermarket.

nbaztec commented: Nice way of putting it :) +1
Aia 1,977 Nearly a Posting Maven

could you please tell me how to pass it back to the main ??,i would be grateful

Strictly speaking "pass it back to the main" would be returning that filepointer.

FILE *open(FILE *opensesame)
{
    opensesame = fopen(/* blah, blah */); /* check return at main */
    return opensesame; /* will return NULL if not successful */
}

where at main: FILE *file_handle = open(file_handle); However you could make use of indirection. And avoid returning.

void open(FILE **opensesame)
{
    *opensesame = fopen(/* blah blah */); /* check NULL at main */
}

where at main:

FILE *file_handle;
open(&file_handle);

Or both

FILE *open (FILE **opensesame)
{
    *opensesame = fopen(/*blah blah */);
    return *opensesame; /* will return NULL if not successful */
}

Where at main: FILE *file_handle = open(&file_handle); If you don't want to return a FILE pointer, but rather another value type and still change the FILE pointer in main

int open (FILE **opensesame)
{ 
    int integer;
    *opensesame = fopen(/*blah, blah */);
    /* blah and more blah */
    /* if blahblah */
    /* else blah blabling */
    return integer;
}

Where at main:

FILE *file_handle;
int check;

check = open(&file_handle);
Aia 1,977 Nearly a Posting Maven

And sorry guys but which libraries I should include for srand(), cout, fork() and rand()? - It gets me errors, it says that those functions are not declared.

This is not a C programming source any longer; it has metamorphosed into something else. There's a dedicated forum for such creature. Look for C++. Post there.

Aia 1,977 Nearly a Posting Maven

fork() requires the header file <unistd.h>

Aia 1,977 Nearly a Posting Maven

Do you have a current user password? Is this a virtual appliance that you downloaded already made?


didi00> But it just doesn't find the file.
Which doesn't find the file, ls -ll or gcc command?

Aia 1,977 Nearly a Posting Maven

You should read the 'Read me first" thread before you post here. http://www.daniweb.com/forums/thread78060.html
In particular, it is much easier for us to read your code if you use the CODE-tags as described in that thread.

Now you are encouraged to use the "Bad Flag Post" button, to let the moderators deal with that issue of proper code tags. It prevents "chastisement" from regulars or not so regulars, and improves the overall atmosphere of "too many Chiefs and too little Indians"

Ancient Dragon commented: right. +28
Aia 1,977 Nearly a Posting Maven

What are you trying to do (to learn)? The posted snippet is quite broken, therefore, hard to guess your intention with it.
What do you think is supposed to happen and it is not occurring?

Aia 1,977 Nearly a Posting Maven

Yes, you can assign different pointer, however you are not doing so.

char* latitude,longitude, ns;

That expands to

char *latitude;
char longitude;
char ns;

Do you see the problem? Only the first declaration is a pointer, the rest are just regular chars.

Aia 1,977 Nearly a Posting Maven
[B]speedy94519>[/B] Well my code is obviously wrong since iam an amateur programmer (about a month now learning it)

We all have been there. The only difference in code, between an amateur and season programmer is that instead of being "obviously wrong", is being, "not so obviously", wrong.

Concerning your particular case. I suggest you approach the issue as follow:

Obtain the line from file
Sanitize it, making it conform a pattern (eliminate blank, substitute unwanted chars, etc)
Use the pattern to extract information
Save information
Then, compare, sort, play, do whatever you want with it.
Aia 1,977 Nearly a Posting Maven

speedy94519> So now I want to compare each element to see if it does have a blank space, and if it does i want to ignore it by incrementing some random variable, and if it isnt I want to put it into a new array so I could print the contents of the file without space.

Still wondering about what you want, nevertheless, maybe this concept can help. It is a naive approach; do not try to pass it a literal string.

#include <stdio.h>
#include <ctype.h>

char *sanitizer(char *src);

int main (void)
{
    char text[] = "Many spaces in between";

    printf(">>%s<<\n", sanitizer(text));

    return 0;
}

char *sanitizer(char *src)
{
    char *scout = src;
    char *group = src;

    /* walking though string */
    while (*scout) {
        if (isspace(*scout)) {
           /* space found skip ahead */
            ++scout;
        } else {
           /* coping none blank char */
            *group++ = *scout++;
        }
    }
    *group = '\0'; /* make it a string in c */
    
    return src;
}
kvprajapati commented: Helpful! +9
iamthwee commented: Most effective and simplest solution +11
Aia 1,977 Nearly a Posting Maven

that's why we HELP for FREE.

don't you have some sort of academic integrity policy at your school? I'm sure paying for homework is in violation of that.

i just turned in someone to their engineering dean and course professor for this.

He called you buddy! Doesn't everybody know that you only have one buddy, and it has stripes, and camouflages itself as a stuff animal when normal people is around?

Here's another one getting ripe for failure. No paying attention to
Narue> Offering to pay someone to do your homework is the kiss of death around here.

Aia 1,977 Nearly a Posting Maven

Bug #590374:
When you are in, replying to a thread. If you scroll down to the previous code, the (Toggle Plain Text) doesn't work. Clicking on it will jump to the open message box. It makes it very hard to copy and paste clean (without #) simple portion of posted code.

Aia 1,977 Nearly a Posting Maven

Yeah I've tried the code above and it says that directory or file *.c doesn't exist.
My kubuntu is in a VirtualBox, does that has to do someting with why it isn't working properly?

The fact that it is running in a VirtualBox does not have a bearing in your problem.
Then file1.c did not get saved or did not get saved in the current directory you are trying to compile or list, whichever you are referring to by "tried the code above".
Write your source code again and make sure where you save it as a *.c file
Navigate to that directory using a terminal. Then give it the gcc command.

Aia 1,977 Nearly a Posting Maven

goodlord, do NOT reinstall your OS. and you're wasting your time with g++ unless you want to compile C++ (.cpp) files. the simple fact is just that your gcc is obviously not able to see your file1.c, and there has to be a simple explanation.

As a side note, I found somehow insightful the comment of her willingness to re-install the OS just because it is easier to do so than to create a password, given current knowledge. It came to my mind that some GNU/Linux distribution has come a long way.

Aia 1,977 Nearly a Posting Maven

I get it. sudo is some kind of root password (which in my case I don't know it). I guess I'll re-install kubuntu and I'll see where to set my root password. I think that I didn't set any password when I installed kubuntu. Oh well...

Kubuntu doesn't have a root account set up by default. The first user account installed becomes a vicarious root user by entering the command sudo every time it requires root privilege. When you enter sudo, the password is asking for, is your password as a user.

didi00> Try sudo-apt get install <selected package>
The proper command is:

sudo apt-get install g++
Aia 1,977 Nearly a Posting Maven

Are you running gcc in the same directory where file1.c is?

Aia 1,977 Nearly a Posting Maven

didi00> I saved it in documents like file1
Save c source code as *.c (i.e. file1.c) then

gcc file1.c -o file1

Where file1 will be the output.

Aia 1,977 Nearly a Posting Maven

The real bug is not checking the return from fopen() before continuing. Had you had done that, no segmentation fault would had occurred.

inp = fopen(first_file, "r");
if ( inp == NULL ) {
    /* Cannot continue, produce error, recover or exit */
}
outp = fopen(second_file, "w");
if ( outp == NULL ) {
   /* Can not write into it, handle the error */
}

Another bug

scanf("%s", first_file);
scanf("%s", second_file);

scanf() stops at the sight of a whitespace. That means you can not enter a file name that contains such.

tux4life commented: :) +8
Aia 1,977 Nearly a Posting Maven

I noticed that this code work for a single citizen, but I'm not sure if it's totally correct. Also I should generalize this code, let's say to 10 citizens for example. In that case i think I have to create an array of 10 CITIZEN structures and it has to do with pointers and their increment, but i'm not "seeing" how to do it.
if anyone could give me a hand with this I would be very grateful.

No need to play with incrementing pointers yet.

/*
 * main should explicitly return an int
 * notice the int, the void and the return
 * at the end
 */ 
int main(void) {

 CITIZEN cit[10];   /* Who ordered ten cits? Coming right up! */ 
 int x, size;       /* x to track the current cit */
 size = sizeof cit / sizeof (*cit); /* ensures always the right count */

/*
 * process the cit one by one
 * notice the use of size to get the next subscript of cit
 * and for loop control
 */
for (x = 0; x < size; x++) {
     insert_personal_info(&cit[x]);
     /* display can be here or outside in another loop after */
     display_cit(&cit[x]); 
 }
 return 0;
}

/* a possible implementation of display_cit() shown above */
void display_cit (CITIZEN *individual)
{
    /* added a break line for clarity */
    printf("Name = %s\n", individual->prs_inf.name);
    printf("Age = %d\n", individual->prs_inf.age);
    printf("Height = %d\n", individual->prs_inf.height);  
}

Of course, your choice of scanf() to read an int is going …

Aia 1,977 Nearly a Posting Maven

Thanks a lot! =)
One question - is C/C++ used to program the Arduino Board? or does it have it's own language?

It has its own language based on C/C++

Aia 1,977 Nearly a Posting Maven

thank you

Part of the functionality of a function relies on the ability to perform a task as independently as possible.
If you notice, your strcat() depends on, and calls strlen(), which is external to it.

A more functional strcat() would call for the use of not such external sources.
Can you think of a way of making it so?

Aia 1,977 Nearly a Posting Maven

speedy94519> do you guys any suggestions how i could return the arrays contents???
Yes, make str3 to point to the destination. Work with that pointer and then return destination.

char* strcat(char *to, const char* from) {
    /* Declarations */
    int length_1,length_2,i;
    char *str3;


    /* Get the length of each string */
    length_1 = strlen_again(to);
    length_2 = strlen_again(from);

    /*
     * point to the destination
     */
    str3 = to;

    /*
     * since you know already the length of the content
     * on destination, use it to start there
     */
    str3 = str3 + length_1;

    for (i=0;i < length_2;i++) {
        *str3 = from[i]; /* copy next char into destination */
        ++str3; /* advance the start point */
    }
    *str3 = '\0'; /* don't forget to make it a string */

    return to; /* to points still to the beginning of destination */
}

Corrected some of your code to show you a possible way.

By the way:

printf("The concatenated string is: %d", strcat(first_choice,second_choice));

Will not display what is intended. But...

printf("The concatenated string is: %d", strlen(strcat(first_choice,second_choice)));

will.

Aia 1,977 Nearly a Posting Maven

Now I didn't know that. I guess that's why I keep coming back.

sizeof is an unary operator and not a function, the parenthesis are only necessary for precedence sake.

[Edit:]
Missed this point from Salem

> 4. sizeof() ; function says it all . It means size of the "data" in this case "words".
sizeof is an operator, not a function.

Which makes my comment redundant and unnecessary.


lionaneesh>Sizeof: http://www.ncl.ucar.edu/Document/Functions/Built-in/sizeof.shtml
That links to a page explaining a function for NCL programming language, and not ANSI C

Aia 1,977 Nearly a Posting Maven

endritius> Also isn't that the declaration before main of the function is supposed to tell the compiler that a function below main has to be linked and there should be reserved three places in memory for three variables.
Not exactly. A function prototype is a concept "borrowed" from other language to help catching errors. It is a signature of what's expected to find once it gets to the function definition. Nothing about reserving memory, nothing about below main.

endritius> The names here are not important if I'm not mistaken.
Identifier names are not necessary in a prototype, however it is a good practice since it helps the programmer. Nevertheless, gerard4143 did point to you something different.
If

void product (float x, int y, float *prd)

then

void product (float, int, float *);

Your were providing the wrong type to the prototype, by just missing that (*)

Aia 1,977 Nearly a Posting Maven

Thats it! Thant what I needed to know. Thanx.

Don't get discouraged! Keep trying!
To read string input (text, word, etc...) from user the function you can try is fgets()
example

char answer[32];
fgets( answer, sizeof answer, stdin );

A caveat with getting input is the `ENTER' key which is returned to any function like a new-line char ('\n'). fgets() includes it if there's room in the buffer.
Removing it is a must if you need to compare with some other string.
A common way of removing it might be

#include <string.h>
if ( fgets( answer, sizeof answer, stdin ) != NULL ) {
     size_t len = strlen ( answer );
     if ( answer[len -1] == '\n' ) {
         answer[len -1] = '\0';
     }
}

Why Am I telling you all this? Because, you need to compare strings at some point. strcmp() is your function for it.

typedef enum {black, brown, red, orange, yellow, green, blue, violet, gray, white} color_code_t;

The name of those colors are not real strings, there are numbers, integers camouflaged in a layer of abstraction so you don't have to deal with the number per se.

Aia 1,977 Nearly a Posting Maven

[...] My goal is for the program to [a]ccept the color spelled out and convert that to a numeric value.

Bingo!

Most likely the nonsense is due to the input received by scanf() containing chars type. In any case when scanf() fails garbage are in those variables, and that's what gets computed and printed.

Sorry, buddy! It doesn't work like that. And scanf() is not your friendly function to get string input. You are asking scanf to read some integers not some names.

Aia 1,977 Nearly a Posting Maven

Like I said, it seemed to run fine for me (I compiled using Code Blocks, which linked math.h for me).

Most likely the nonsense is due to the input received by scanf() containing chars type. In any case when scanf() fails garbage are in those variables, and that's what gets computed and printed.

Aia 1,977 Nearly a Posting Maven

A couple questions and a statement.
Is your compiler or you linking the math library for the pow() function?

What do you enter at the first prompt? A number (integer) or the label? Do you enter `blue' or do you enter `6'?

Here's the statement. You need to uncomment the stdio.h header file if you want printf(), and scanf() to work.

Aia 1,977 Nearly a Posting Maven
*(unsigned int*)&recvline[0] = 11111;

*(unsigned int*)&recvline[sizeof(unsigned int)] = 22222;
/*this section*/
*(void(**)(void))&recvline[2 * sizeof(unsigned int)] = (void(*)(void))&myhello;
/*this section*/

Casting is not for l-value. Only for r-value.

Aia 1,977 Nearly a Posting Maven

realloc() only works with memory that has been previously allocated with malloc(), calloc() or realloc()

ProtocolReceiveBuffer = realloc(ProtocolReceiveBuffer, (rows)*sizeof(unsigned int*));

It is not recommended to use the same pointer to reallocate memory. If it fails you have lost the point to that memory creating a memory leak.

Aia 1,977 Nearly a Posting Maven

uh... not so much :)

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
   FILE *fp_source, *fp_dest;
   char oneByte;

   /* WARNING:  this does ZERO error checking!! */

   fp_source = fopen(argv[1], "rb"));
   fp_dest   = fopen(argv[2], "wb"));

   while(!feof(fp_source)) {
      oneByte = fgetc(fp_source);
      fputc(oneByte, fp_dest);
   }

   fclose(fp_source);
   fclose(fp_dest);

   return 0;
}

.

How about stopping the loop without the !eof() ? eof() is not a good solution as the exit control of a loop. EOF would be true only after it is read and not when it is reached. char oneByte; must be an int, since fgetc() returns an int, and it is not a guarantee that char would be signed.

Aia 1,977 Nearly a Posting Maven

facesInhand is not the same than facesInHand

jephthah commented: damn, you're good. +7
Aia 1,977 Nearly a Posting Maven

I've uploaded one of the sample files, in case it helps.

The file has been encoded as an Unix text file the contains only the newline which representation can be \n at the end of each line.
Windows text files represent the new line using two characters \r\n Both are invisible when displaying the information.

Aia 1,977 Nearly a Posting Maven

But if in notepad, something appears on the next line, doesn't there have to be a /n character? What's /br?

Do a test.
Open Notepad.
Write a line; press enter.
Write another line; press enter
One more time. Write a line; press enter.

Do you see a \n anywhere? Are there any new lines?

Aia 1,977 Nearly a Posting Maven

For my assignment, I have download a .txt file from my prof's webpage, and then have my program open it. The file, when opened in a web browser, appears as follows:<br />
<br />
87.0<br />
94.5<br />
55.6<br />
88.0<br />
82.0<br />
91.0<br />
etc.<br />

<br />

When you view the source of your post this is what it displays.
There's no newline.
Think about it.

Aia 1,977 Nearly a Posting Maven

Hmm. thanks for that - kind of obvious, I guess! Now adapted to my actual needs and incorporated where required.

Yes, it needs adaptation. I left the part where it deals with spaces for you.

Aia 1,977 Nearly a Posting Maven

In the code snippet:

int Z;
boolean ParsedOk;
ParsedOk = sscanf( CommandLine, "%i", &Z ) == 1;

[...]
How can I detect (and reject) such malformed numerical input?

Check for trailing input as well.

if (sscanf(CommandLine, "%d%c", &Z, &ch) == 2 && (ch == '\n' || ch == '\0')) { 
    /* We got a winner */
} else {
    /* Anything else is uncivilized */
}
Aia 1,977 Nearly a Posting Maven
/*  A program to count the number of grades occurring in the input */

#include <stdio.h>
#define DEBUG

int main()
{
  /* Declare variables */
  int a;
  int b;
  int c;
  int d;
  int f;
  int others;
  int ch; /* for input */
 
       /* Initialize variables at zero */
       a = b = c = d = f = 0;
       others = 0;

       /* While c is a character and not equal to end of file */
       while ((ch = getchar()) != EOF && ch != '\n')
       {

        /* Print all characters read */
        printf("%c", ch); /* I removed the '\n' to make it appear as you wanted */

              /* Count inputs */
              switch(ch)
              {
                 case 'a': 
                 case 'A':a++; break;
                 case 'b': 
                 case 'B':b++; break;
                 case 'c': 
                 case 'C': c++; break;
                 case 'd': 
                 case 'D':d++; break;
                 case 'f': 
                 case 'F': f++; break;
                 default: others++; break;
              }
       }
       putchar('\n'); /* add a new line to display the result in its own line */

       /* Print results */
       printf("Grade counts:\n");

       printf("  A's: %d\n", a);
       printf("  B's: %d\n", b);
       printf("  C's: %d\n", c);
       printf("  D's: %d\n", d);
       printf("  F's: %d\n", f);
       printf("  Other grades: %d\n", others);

       return 0;
}

A few errors you had. Take a look at the red notations.
The while loop needs to have a way to stop that it is not only the EOF. If not, you can not see the result. '\n' seems adequate to me.
You need to break in the switch after every …

Aia 1,977 Nearly a Posting Maven
/************bubble sort******************************************************/
void bubblesort ( int i){
     
     int x,y,j;
     float temp;
     char buff[BUFSIZ];
     float a[N];
     FILE *in;
     in=fopen("rand.txt","r");
   
    i=0;
    while(fgets(buff,BUFSIZ,in)!=NULL){
          a[i]=atof(buff);
	      i++;
    }

Let me analyze the first fifteen lines. void bubblesort ( int i){ That i parameter will become a copy of the argument, since you assign 0 to it before using it, there's not much sense on that parameter.

void bublesort (void) {
    int i = 0;
}

There's no provision to prevent blowing out the array a.
If rand.txt contains more lines that N you would be writing into memory that you should not.

/* the while loop will continue even if a[] is full */
while(fgets(buff,BUFSIZ,in)!=NULL){
       /*
        * atof() returns 0.0 
        * if it can not convert successfully           
        * it needs to be checked before assigning it to a[]
        */
        a[i]=atof(buff);
        i++;
jephthah commented: nice work, as usual +6