?
Solved

starting C programming question

Posted on 2003-03-16
20
Medium Priority
?
164 Views
Last Modified: 2010-07-27
if ( argv[2] =='-last'){
     type =='1';
}
if ( argv[2] =='-age'){
     type =='3';
}
if ( argv[2] =='-first'){
     type =='2';
}
if ( argv[2] !='-first' || argv[2] !='-last' || argv[2] !='-age' ){
 printf("Usage: names <size> [flag]\n");
}

Would the above work?  I'm just trying take the command line input...if its -last for example..i want to set type = 1 for later use...right now it says comparison makes pointer and integer error
0
Comment
Question by:AZN_Wang2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 8
  • 2
20 Comments
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 8148579

The concept is OK, but C doesn't support comparison of strings with '=='.  And strings should be enclosed by double-quotes.

Replace the first "if" statement with this one, and use the same type of structure with the other string compares.


if (strcmp (argv[2], "-age") == 0)


Good Luck,
Kdo
0
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 8148589
Whoops.  Didn't see the first "if" way off to the right.

My example is for the second "if".


Kdo
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8148604
i understand what u r trying to do .. but above wont work ..
in C u cannot compare strings like this
argv[2]=='-last';
 for 2 reasons
u cannot comapre strings with == sign .. and '-last' is not a string constant "-last" is .. double quotes are required..

so if u want to compare argv[2] to be equal to "-last"
u shud do
if(!strcmp(argv[2],"-last")){
printf("argv[2] is = -last");
// do ur stuff
}

to use strcmp .. u have to
#include <string.h>

and also since u expect ur user to pass one of the three arguments.. u can have single conditional check to see if proper arguments have been passed.

if(argc>3){ // number of arguments expected including program name
if(!strcmp(argv[2],"-last"){
//set ur type
}
else if //same like above

}
else if//same like above

} else {
// u can tell that either of the words last/ age or first are required
}

}else{
//print usage
}

try it out and let us know when u r stuck
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 8

Expert Comment

by:akshayxx
ID: 8148616
>> type =='1';
this is also wrong
this should be
type='1';
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8148628
u might have figured out it as yet.
but this is also wrong
 argv[2] !='-first'

for further details .. see man strcmp ..
http://www.die.net/doc/linux/man/man3/strcmp.3.html

its similar on windows also.
0
 

Author Comment

by:AZN_Wang2
ID: 8148691
void check_args(int argc, char **argv,int *num,int *type){
int i;




for(i=0; argv[1][i] !='\0';i++){

     if (isdigit(argv[1][i]) == 0){
 printf("Usage: names <size> [flag]\n");
 exit (-1);
     }

}


*num = atoi(argv[1]);



if(argc < 2 || argc > 3){
     printf("Usage: names <size> [flag]\n");
exit (-1);
}


if(!strcmp(argv[2],"-last")){
*type=1;
}

if (!strcmp(argv[2],"-age")){
*type=3;
}


if(!strcmp(argv[2],"-first")){
     *type =2;

}

printf("%d\n",&type);


i think i'm doing something terribly wrong! lol...if i just type
program...it returns a seg fault
if i type program 3d..it will return the error message
if i type program 3 ...it will continue to work
=/
sorry..really dumb when it comes to C
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8148740
first of all tell us
do u want ur parameters
age last first .. all in the list .. or only one of them .. at one run?
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8148746
ignore my above question .. i u need only one at a time .. thats why type..
tell me whats ur sample input ..
whats argv[1] on which u r trying atoi
show the sample input
0
 

Author Comment

by:AZN_Wang2
ID: 8148765
First change. The size and sort type is given to the program via command line
arguments. The usage is :

Usage: names <size> [flag]

where size is the amount of names and this must be there. The flag argument
is optional. If there is no flag argument then the default sort is by
lastname. The flags tell the program what to sort by, the different flags
are
     -last
     -first
     -age

Good usage:
names 34
names 32 -age
anmes 100 -first

Bad usage:
names
names foo
names 34 -last -first
names 32 -lost
names 29f

i alreayd wrote the rest of the program from last assignment...right now i want type set to 1 if command argv[2] is -last....2 if its -first, 3 if its -age and set type to 1 if there is no argv[2]...and pring usage if its a bad argv[2] input such as -stuipd

thanks so much for your help

0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8148802
look at the following modifications to ur code . with comments

void check_args(int argc, char **argv,int *num,int *type){
int i;
char *endptr;




*num=(int)strtol(argv[1],&endptr,10);

if(endptr!=NULL) //printf that argv[1] wasnt proper integer
//check the man page of strtol and also .. include stdlib.h to use this


if(argc < 2 || argc > 3){
    printf("Usage: names <size> [flag]\n");
exit (-1);
}


if(!strcmp(argv[2],"-last")){
*type=1;
}

if (!strcmp(argv[2],"-age")){
*type=3;
}


if(!strcmp(argv[2],"-first")){
    *type =2;

}

printf("%d\n",*type);
// to access value from pointer u shud use *ptr ( dereferencing)
and not &ptr ( taking value of address)
0
 

Author Comment

by:AZN_Wang2
ID: 8148875
for(i=0; argv[1][i] !='\0';i++){

     if (isdigit(argv[1][i]) == 0){
 printf("Usage: names <size> [flag]\n");
 exit (-1);
     }

}

*num=(int)strtol(argv[1],&endptr,10);

if(endptr!=NULL) {
     
}//printf that argv[1] wasnt proper integer
//check the man page of strtol and also .. include stdlib.h to use this


if(argc < 2 || argc > 3){
   printf("Usage: names <size> [flag]\n");
exit (-1);
}


if(!strcmp(argv[2],"-last")){
*type=1;
}

if (!strcmp(argv[2],"-age")){
*type=3;
}


if(!strcmp(argv[2],"-first")){
   *type =2;
}

if( (!strcmp(argv[2],"-first"))==0 || (!strcmp(argv[2],"-age"))==0 || (!strcmp(argv[2],"-last")) ==0 ){
   printf("Usage: names <size> [flag]\n");
}

printf("%d\n",*type);
         
}

thx for your help ash, now i get a seg fault when i type
program
or
program 3
...why is that?
just typing program should return the usage error message
program 3 should work...since the flag or argv[2] is optional
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8148915
can u show the full  code .. main and all .. let me see that .. and we can make it work for u ..
0
 

Author Comment

by:AZN_Wang2
ID: 8148923
names.c:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"names_func.h"


int main(int argc, char *argv[]){

      int type,num;
      char **names;

      /*Check if command line arguments are correct
      * and find the number of names and type   */
      check_args(argc,argv,&num,&type);
      
      /*Allocate Space for the names*/
      names = allocate(num);

      /*Get the names for the users*/
      getnames(names,num);

      /*Sort the names*/
      sort_names(names,num,type);

      /*Print the sorted array out*/
      print_names(names,num);

      return 0;
}


names_func.c:

#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include"names_func.h"

void check_args(int argc, char **argv,int *num,int *type){
int i;
char *endptr;



for(i=0; argv[1][i] !='\0';i++){

      if (isdigit(argv[1][i]) == 0){
 printf("Usage: names <size> [flag]\n");
 exit (-1);
      }

}








*num=(int)strtol(argv[1],&endptr,10);

if(endptr!=NULL) {
      
}//printf that argv[1] wasnt proper integer
//check the man page of strtol and also .. include stdlib.h to use this


if(argc < 2 || argc > 3){
   printf("Usage: names <size> [flag]\n");
exit (-1);
}


if(!strcmp(argv[2],"-last")){
*type=1;
}

if (!strcmp(argv[2],"-age")){
*type=3;
}


if(!strcmp(argv[2],"-first")){
   *type =2;
}

if( (!strcmp(argv[2],"-first"))==0 || (!strcmp(argv[2],"-age"))==0 || (!strcmp(argv[2],"-last")) ==0 ){
   printf("Usage: names <size> [flag]\n");
}

printf("%d\n",*type);
            
}




 int allocate(int numbers){
int num;
numbers = (int *) malloc ( sizeof ( int ) * num ) ;

return numbers;
}


// gets names from user and stores in string
void getnames(char names[][LEN], int num){

  int i;
  for(i=0;i<num;i++){
    printf("Enter name %d:", i+1);
    scanf("%s", names[i]);
  }
}
// sorts names from user  
void sort_names(char names[][LEN], int num, int type){

  int i=0;
  int  j=0;
  int a;
  int b;
  int x;
  char first[MAX][FIRST+LAST];
  char last[MAX][LAST+FIRST];  
  char age[MAX][AGE+LAST+FIRST];
  char temp[FIRST+LAST+AGE];
  char temp2[LEN];
  int itemp=0;

  for(x=0;x<num;x++){
    i=0;
    j=0;

    while(names[x][i]!=','){
      i++;
      j++;
    }
// copies the last name into string last
    strncpy(last[x], &names[x][0], i);
    last[x][i] = '\0';

    while(names[x][j+1]!=','){
      j++;
    }
   
// copies first name into string first
    strncpy(first[x], &names[x][i+1], j);
    first[x][j-i] = '\0';
    strcat(first[x],last[x]);
   
// copies age into string age
    strcpy(temp, &names[x][j+2]);
    itemp = atoi(temp);
    sprintf(age[x],"%2d",itemp);
    strcat(age[x],last[x]);
    strcat(age[x],first[x]);
  }
 
  switch(type){
// sort by last name and then first
    case 1:
      for(b=0;b<num+1;b++){
        for(a=0;a<num-1;a++){
          if(strcmp(last[a],last[a+1])==0){
            if(strcmp(first[a],first[a+1])>0){
              strcpy(temp,first[a]);
              strcpy(first[a],first[a+1]);
              strcpy(first[a+1],temp);
              strcpy(temp,last[a]);
              strcpy(last[a],last[a+1]);
              strcpy(last[a+1],temp);
              strcpy(temp2,names[a]);
              strcpy(names[a],names[a+1]);
              strcpy(names[a+1],temp2);
      } } } }
      for(b=0;b<num+1;b++){
        for(a=0;a<num-1;a++){
          if(strcmp(last[a],last[a+1])>0){
            strcpy(temp,last[a]);
            strcpy(last[a],last[a+1]);
            strcpy(last[a+1],temp);
            strcpy(temp2,names[a]);
            strcpy(names[a],names[a+1]);
            strcpy(names[a+1],temp2);
      } } }
      break;


//  sort by first name then last
    case 2:
      for(b=0;b<num;b++){
        for(a=0;a<num-1;a++){
          if(strcmp(first[a],first[a+1])>0){
            strcpy(temp,first[a]);
            strcpy(first[a],first[a+1]);
            strcpy(first[a+1],temp);
            strcpy(temp,last[a]);
            strcpy(last[a],last[a+1]);
            strcpy(last[a+1],temp);
            strcpy(temp2,names[a]);
            strcpy(names[a],names[a+1]);
            strcpy(names[a+1],temp2);
      } } }
      for(b=0;b<num;b++){
        for(a=0;a<num-1;a++){
          if(strcmp(first[a],first[a+1])==0){
            if(strcmp(last[a],last[a+1])>0){
              strcpy(temp,last[a]);
              strcpy(last[a],last[a+1]);
              strcpy(last[a+1],temp);
              strcpy(temp2,names[a]);
              strcpy(names[a],names[a+1]);
              strcpy(names[a+1],temp2);
      } } } }
      break;

// sorts by age then last name then first
    default:
      for(b=0;b<num;b++){
        for(a=0;a<num-1;a++){
          if(strcmp(age[a],age[a+1])>0){
            strcpy(temp,age[a]);
            strcpy(age[a],age[a+1]);
            strcpy(age[a+1],temp);
            strcpy(temp2,names[a]);
            strcpy(names[a],names[a+1]);
            strcpy(names[a+1],temp2);
      } } }
      for(b=0;b<num;b++){
        for(a=0;a<num-1;a++){
          if((age[a]) == (age[a+1])){
            if(strcmp(last[a],last[a+1])>0){
              strcpy(temp,last[a]);
              strcpy(last[a],last[a+1]);
              strcpy(last[a+1],temp);
              strcpy(temp2,names[a]);
              strcpy(names[a],names[a+1]);
              strcpy(names[a+1],temp2);
      } } } }
      break;
  }
}


void print_names(char names[MAX][LEN], int num){

  int i;

  for(i=0;i<num;i++){
    printf("%s \n",names[i]);
  }
}
0
 
LVL 8

Accepted Solution

by:
akshayxx earned 300 total points
ID: 8149019
well there are a lot of errors in your program .. like i dont see the

but let me tell u first the first of the potential reason of the segmentation fault
in check_args.. u are straight away accessing argv[1].. which is not present if u call like this
program <no arguments>

so u shud first check on the number of arguments expected . then only u shud proceed

like this
if(argc< 3){ then abort}
else {proceed}


also u dont need to check isdigit for each character of argv[1]. for that purpose only i have shown u the use of
strtol..
it returns the pointer to first invalid character in the  argv[1] ..in the variable endptr.. else endptr is set to NULL if the string is parsed OK to be integer
so check if endptr!=NULL then  the number had some problem .. non-digit characters..

another error that i can see is in ur allocate
it should be like this
int * allocate( int num){
int * numbers;
numbers = (int*) malloc( sizeof(int)*num));

return numbers; // do the error checking .. if it malloced properly or not
}

also when u r using allocate .. u are trying the get the returned value in char** .. while in allocate u want to allocate array of integers..
so make sure what do u want to allocate .. and to what u want to assign

try these things first .. and good luck ..
0
 

Author Comment

by:AZN_Wang2
ID: 8149533
char * allocate( int num){
int * numbers;
numbers = (char *) calloc (num, sizeof(char));

return numbers;
}

Thx for your help...i got the rest working now =)
but a compile question on this one

names_func.c:69: warning: assignment from incompatible pointer t
names_func.c:71: warning: return from incompatible pointer type

it points to
69:numbers = (char *) calloc (num, sizeof(char));

71:return numbers;
0
 

Author Comment

by:AZN_Wang2
ID: 8149568
fd
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8149575
check the type of numbers
it should be declared as
char * numbers;

if u wanna assign it as
numbers (char*)calloc(num,sizeof(char));

and if its int* then u shud use proper type-cast
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8149577
>>numbers (char*)calloc(num,sizeof(char));
forgot the '=' sign

numbers = (char*)calloc(num,sizeof(char));
0
 

Author Comment

by:AZN_Wang2
ID: 8149579
err...i found the problem...suppose to be char * numbers =)
...
i got a problem where if the names array is over 8(columns)..i get a seg fault =/
why is that?
0
 

Author Comment

by:AZN_Wang2
ID: 8149598
I get a Seg Fault when the test scripts reaches test 9...
the rest of my test works....this is for the names prog btw



when i run gdb, it says thiStarting program:
/home/yanghai/ecs30/p5/names 9
Enter name 1:lkdsjfladsfjlksdj,3jkl3jlk4jlk3j4,3
Enter name 2:lkjlksdfjlkdlsflsdfj,jlkjlkjkljlkkl3,3
Enter name 3:klsdfjlkjsdlflsk,jlkdsfjlksdjflkjlskdfj,5
Enter name 4:jsdlkflksdhgsdl,sdjflkjdskljflsdjlkfj,3
Enter name 5:kldfjslkfjksdlg,djlkfjskdgjlsdgklh,3
Enter name 6:jdlskjlfgsdhglklksdghl,343,3
Enter name 7:ldskjfksjdklfjsldflk,3434343j,3
Enter name 8:ksdjglksdhgsdhkg,3jlkjlkjkljlk3,3
Enter name 9:lskdglkdslghsledg,8,7

Program received signal SIGSEGV, Segmentation fault.
0x400c49dd in strcpy () from /lib/libc.so.6

what does this mean?
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.
Suggested Courses

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question