Page 1 of 2 12 LastLast
Results 1 to 10 of 13

Thread: C question: Converting a string to a unsigned long int?

  1. #1
    Join Date
    Aug 2007
    Beans
    368
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    C question: Converting a string to a unsigned long int?

    Hi! I'm working in a program in C that reads a file like:

    John
    Smith
    55585913


    And then makes some stuff and writes on another file the output.

    In order to read the three values, I first thought in use fscanf,but I realized that that function stopped with a white character, so there could be problems with that. I took a look at fgets , which seems fine because read line by line and returns an string.

    I need to compute something with the numerical value of the text, so I need to convert the string that fgets gives to me to a unsigned long int.

    Any standard library offers me that conversion with a function?


    Thank you very much!!!
    Engineering addict

  2. #2
    Join Date
    Oct 2007
    Location
    California
    Beans
    80
    Distro
    Ubuntu 7.10 Gutsy Gibbon

    Re: C question: Converting a string to a unsigned long int?

    Take a look at:
    atoi
    atol

    You must include stdlib.h

  3. #3
    Join Date
    Aug 2007
    Beans
    368
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: C question: Converting a string to a unsigned long int?

    oh yes! atol it's what I was looking for! Thanks!

    Another newbie question, fgets gives me a line of the textfile which includes the newline character '\n', I would like to remove it from my string. Of course I could do a little function to do that but if theres something on the standard library that makes this work would be fantastic!!

    Thank you very much for your help again! I'm just starting C and I think I like it!
    Engineering addict

  4. #4
    Join Date
    Aug 2007
    Beans
    368
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: C question: Converting a string to a unsigned long int?

    I did start making the little function to remove the newline character from the string that fgets gives me, and I'm having some trouble:

    Code:
    fgets(string_in , MAX_SIZE , texfile);
    
    /* Here I'm trying to remove the 'nl' from string_in */
    
    int i;
    
    for ( i = 0; i < MAX_SIZE ; i++) {
          if ( string_in[i]  == 'nl' ) {
            /* don't know what to do here :( */
    }
    Isn't any function on any library like "remove"? I'm little used to the java way so I don't know how to cope with it

    Thanks for your help!!!
    Engineering addict

  5. #5
    Join Date
    Aug 2007
    Beans
    368
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: C question: Converting a string to a unsigned long int?

    I'm thinking on another way of doing this, I thought I was on the right way doing this:
    Code:
    fgets(string_in , MAX_SIZE , texfile);
    
    /* removes the nl character */
    
    char *nlptr = strchr(string_in,'\n');
    *nlptr = '\0'
    But the compiler says to me: on the line of "char..." : Expression sytax in function main

    I don't understand exactly the problem, I must define before somewhere nlptr?

    Thanks!
    Engineering addict

  6. #6
    Join Date
    Mar 2006
    Location
    Eefde, The Netherlands
    Beans
    432
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: C question: Converting a string to a unsigned long int?

    Quote Originally Posted by fredscripts View Post
    I'm thinking on another way of doing this, I thought I was on the right way doing this:
    Code:
    fgets(string_in , MAX_SIZE , texfile);
    
    /* removes the nl character */
    
    char *nlptr = strchr(string_in,'\n');
    *nlptr = '\0'
    But the compiler says to me: on the line of "char..." : Expression sytax in function main

    I don't understand exactly the problem, I must define before somewhere nlptr?

    Thanks!
    In C90 you cannot declare variables in the middle of a block, you need to declare them at the start of a block. So declare char *nlptr at the start of the function.

    Also, consider using strtoul(3), ato* functions don't indicate whether an error occurred during conversion. You also don't check the return value of fgets(), fgets returns NULL on error, check for it and handle it.

    Next time post the exact error message (copy & paste), don't retype, I have a feeling GCC's error messages don't contain words like 'sytax' (unless you declare an object named 'sytax').
    "When in doubt, use brute force."

    -- Ken Thompson

  7. #7
    Join Date
    Jan 2006
    Beans
    Hidden!
    Distro
    Ubuntu 10.10 Maverick Meerkat

    Re: C question: Converting a string to a unsigned long int?

    I would use fgets to read in a line into a buffer and then sscanf to read stuff from buffer ...
    I am infallible, you should know that by now.
    "My favorite language is call STAR. It's extremely concise. It has exactly one verb '*', which does exactly what I want at the moment." --Larry Wall
    (02:15:31 PM) ***TimToady and snake oil go way back...
    42 lines of Perl - SHI - Home Site

  8. #8
    Join Date
    Jul 2007
    Location
    Martínez, BS AS Argentina
    Beans
    24
    Distro
    Ubuntu 9.10 Karmic Koala

    Re: C question: Converting a string to a unsigned long int?

    I recommend strtoul() to convert the string to unsigned long int. If the string does not represent an unsigned long, with strtoul() you may see if that worked. strtoul() is part of stdlib.h
    Then, to remove the nl:
    Code:
    /*with nlptr declared as: char *nlptr; at the beginning of the function */
    if(( nlptr = strchr( string, '\n' )) != NULL )
      *nlptr = '\0';
    /* it's wrapped by an IF to check if the string really had one. 
    fgets() will read only MAX_SIZE chars, so, it may not read up to a nl char. */

  9. #9
    Join Date
    Jun 2007
    Location
    Maryland, US
    Beans
    6,248
    Distro
    Kubuntu

    Re: C question: Converting a string to a unsigned long int?

    Using strtok() presents a solution as well:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    int main()
    {
      FILE *fp = fopen( "data.txt", "r" );
    
      if ( fp != NULL )
      {
        char buf[ 80 ] = { '\0' };
    
        while ( fgets( buf, sizeof buf, fp ) != NULL )
        {
          char *str = strtok( buf, "\n" );
          printf( "str = %s\n", str );
        }
        fclose( fp );
      }
      return 0;
    }
    If you wish to consider using your strchr() idea, then here's the code:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    int main()
    {
      FILE *fp = fopen( "data.txt", "r" );
    
      if ( fp != NULL )
      {
        char buf[ 80 ] = { '\0' };
    
        while ( fgets( buf, sizeof buf, fp ) != NULL )
        {
          char *nlPtr = 0;
    
          if ( (nlPtr = strchr( buf, (int)'\n' )) != NULL )
          {
            *nlPtr = '\0';
          }
    
          printf( "buf = %s\n", buf );
        }
        fclose( fp );
      }
      return 0;
    }
    Last edited by dwhitney67; November 18th, 2007 at 09:57 AM.

  10. #10
    Join Date
    Dec 2006
    Location
    Australia
    Beans
    1,097
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: C question: Converting a string to a unsigned long int?

    Quote Originally Posted by fredscripts View Post
    I need to compute something with the numerical value of the text, so I need to convert the string that fgets gives to me to a unsigned long int.

    Any standard library offers me that conversion with a function?
    Use the strtoul function, as mentioned in Meneldir's post. Here's a commented example.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
    	/*
    	 * the_str = value to be assigned by console input
    	 * newline = pointer to \n in the_str
    	 * the_ulong = the unsigned long integer
    	 */
    	char the_str [20];
    	char *newline;
    	unsigned long the_ulong;
    
    	/* Fetch user input from console */
    	fgets(the_str, 20, stdin);
    
    	/* Use strchr to find \n in the_str.
    	 * strchr returns NULL if no \n was found.
    	 * If strchr was successful in finding \n:
    	 * 	replace the \n with \0.
    	 */
    	newline = strchr(the_str, '\n');
    	if (newline != NULL) {
    		*newline = '\0';
    	}
    
    	/* Convert the_str to unsigned long and assign to the_ulong.
    	 * Parameters for strtoul:
    	 * 	the_str is the source string
    	 * 	ignore the second parameter, it is not used in this example
    	 * 	10 means base-10, so convert the_str to base-10 unsigned long
    	 */
    	the_ulong = strtoul(the_str, NULL, 10);
    
    	printf("%lu\n", the_ulong);
    
    	return 0;
    }
    Beware that if the string represents a number too big for an unsigned long, your result will not be correct.

    strtoul is supposed to set errno to ERANGE and return ULONG_MAX when converted value is out of range, but it doesn't actually do so!
    Last edited by samjh; November 18th, 2007 at 11:14 AM.

Page 1 of 2 12 LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •