Thread: "scanf" an int but detect string as well

  1. #1
    Registered User
    Join Date
    Feb 2018
    Location
    San Diego, CA
    Posts
    40

    "scanf" an int but detect string as well

    Hey all! Thanks for the continuous help on this forum. I would like to be able to add a part to the scanf when "STOP" is entered to stop and give and then sort int's that have already been inserted. I've been spending a few hours already trying to solve this problem. My book mentions atoi(), also looked into strtol() functions, and also sscanf(). I have wassted enough time on this last part of the program and am asking for immediate help. Thanks to all of the old timers on here posting lengthy replies almost immediately

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX 5
    
    int intcmp(const void *a, const void *b)
    {
        return (*(int *)a - *(int*)b);
    }
    
    int main( void )
    {
        int count, arr[MAX], key, *ptr;
    
        printf("Enter %d integer values; press Enter after each.\n", MAX);
    
        for (count = 0; count < MAX; count++)
            scanf("%d", &arr[count]);
    
        puts("Enter Enter to sort the values.");
        getc(stdin);
    
        // Sort the array into ascending order.
        
        qsort(arr, MAX, sizeof(arr[0]), intcmp);
    
        // Display the sorted array.
        for (count = 0; count < MAX; count++)
            printf("\narr[%d] = %d.", count, arr[count]);
    
        puts("\nPress Enter to continue.");
        getc(stdin);
    
        return 0;
    }
    I've also tried this
    Code:
    scanf("%d %s", &arr[count], string);
    or similar

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    26,237
    Read as a string, then parse the string, say with strtol or sscanf. atoi cannot distinguish an error so don't use it here.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User john.c's Avatar
    Join Date
    Dec 2017
    Posts
    493
    A simple solution is to read an int with scanf and use its failure to indicate the end of input, so the user could type STOP or just x or anything that isn't whitespace or an int to end input.

    Your compare function has a bug as it is possible that a - b will underflow, e.g., if a is -2000000000 and b is 2000000000 then the answer (-4000000000) can't be represented in an int (I'm assuming a 32-bit int here; if they are 64 then the same problem occurs with the squares of those numbers).
    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    #define MAX_SIZE 100
     
    int intcmp(const void *a, const void *b)
    {
        int na = *(int*)a, nb = *(int*)b;
        return (na > nb) - (na < nb);
    }
     
    int main()
    {
        int values[MAX_SIZE];
        int size = 0;
     
        for (int n; size < MAX_SIZE && scanf("%d", &n) == 1; )
            values[size++] = n;
     
        for (int ch; (ch = getchar()) != '\n' && ch != EOF; )
            ;
     
        qsort(values, size, sizeof values[0], intcmp);
     
        for (int i = 0; i < size; ++i)
            printf("%d%c", values[i], i < size - 1 ? ',' : '\n');
    }
    Code:
    6 3 123 7646 2000000000 -211 37 -2000000000 75432 -101010 x
    -2000000000,-101010,-211,3,6,37,123,7646,75432,2000000000
    Last edited by john.c; 12-11-2018 at 09:41 AM.
    Let him who is not come to logic be plagued with continuous and everlasting filth.
    - John of Salisbury, 1160

  4. #4
    Registered User
    Join Date
    Feb 2018
    Location
    San Diego, CA
    Posts
    40
    Hey laserlight! Thanks for the post...

    I was able to get the program to "run" however several warnings and I've learned from this forum not to run programs with errors. I am beginning to become familiar with the string functions using C, using this forum and google for help. Basically, typing "STOP" after program execution will end the program if this line is set:

    Code:
    if (strcmp(str, "STOP") == 0){
        exit(0); // Not sure if program would work successfully if I made this 'break;'
    }
    Also, the program is outputting numbers through the qsort() function but they aren't sorted properly. I gave this program a fair shot and am now asking for help.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAX 5
    
    int intcmp(const void *a, const void *b)
    {
        return (*(int *)a - *(int*)b);
    }
    
    int main( void )
    {
        int count = 0;
        char str[15][15];
        long ret;
    
        char *ptr2;
    
        printf("Enter %d integer values; press Enter after each.\n", MAX);
    
        for(count = 0; count < MAX; count++)
        {
            scanf("%s", str[count]);
            {
                if (strcmp(str, "STOP") == 0)
                {
                    break;
                }
                else
                {
                    continue;
                }
            }
        }
    
        ret = strtol(str, &ptr2, 10);
        
        puts("Enter Enter to sort the values.");
        getc(stdin);
    
        // Sort the array into ascending order.
        
        qsort(str, MAX, sizeof(str[0]), intcmp);
    
        // Display the sorted array.
        for (count = 0; count < MAX; count++)
            printf("\nstr[%d] = %s.", count, str[count]);
    
        puts("\nPress Enter to continue.");
        getc(stdin);
    
        return 0;
    }
    Also...if 'STOP" isn't entered immediately after program execution, the program never ends. i.e. str[0]

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    36,838
    You need to fix the warnings in your code.
    Code:
    $ gcc -Wall foo.c
    foo.c: In function ‘main’:
    foo.c:26:24: warning: passing argument 1 of ‘strcmp’ from incompatible pointer type [-Wincompatible-pointer-types]
                 if (strcmp(str, "STOP") == 0)
                            ^
    In file included from foo.c:3:0:
    /usr/include/string.h:140:12: note: expected ‘const char *’ but argument is of type ‘char (*)[15]’
     extern int strcmp (const char *__s1, const char *__s2)
                ^
    foo.c:37:18: warning: passing argument 1 of ‘strtol’ from incompatible pointer type [-Wincompatible-pointer-types]
         ret = strtol(str, &ptr2, 10);
                      ^
    In file included from foo.c:2:0:
    /usr/include/stdlib.h:183:17: note: expected ‘const char * restrict’ but argument is of type ‘char (*)[15]’
     extern long int strtol (const char *__restrict __nptr,
                     ^
    foo.c:16:10: warning: variable ‘ret’ set but not used [-Wunused-but-set-variable]
         long ret;
              ^
    > if (strcmp(str, "STOP") == 0)
    Try comparing with str[count]

    > ret = strtol(str, &ptr2, 10);
    What are you hoping to achieve with this?

    > qsort(str, MAX, sizeof(str[0]), intcmp);
    What?
    Your compare function is expecting integers, but your array is still strings.

    Crudely,
    Code:
    char dummy[10];
    int arr[MAX];
    for ( i = 0 ; i < MAX ; i++ ) {
        if ( scanf("%d",&arr[i]) == 1 ) {
            // success
        }
        else if ( scanf("%s",dummy) == 1 && strcmp(dummy,"STOP") == 0 ) {
            // wasn't an int, but it was the string "STOP"
            break;
        }
    }
    // now sort and print 'i' elements of arr[]
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A "Simple" Array/String Problem. "Help" ASAP needed
    By AirulFmy in forum C Programming
    Replies: 10
    Last Post: 08-19-2015, 04:30 AM
  2. Replies: 8
    Last Post: 04-12-2015, 10:28 AM
  3. Replies: 46
    Last Post: 08-24-2007, 04:52 PM

Tags for this Thread