0

I am trying to write a c program. It have to enter two arrays and input should be space seperated. I tried somehow to eliminate the '\n'.

#include <stdio.h>

int main()
{
    char temp;
    int alc[3]={0}, bob[3]={0}, i=0;

    //enter alice 
    do 
    {
        scanf("%d%c", &alc[i], &temp);
        i++;
        } while(temp != '\n');

    i=0;

    //enter bob
       do 
    {
        scanf("%d%c", &bob[i], &temp);
        i++;
    } while(temp != '\n');

    //print alice
    for(i = 0; i < 3 ; i++)
    {
            printf("%d ", alc[i]);
    }

    //print bob
    for(i = 0; i < 3 ; i++)
    {
            printf("%d ", bob[i]);
    }


    return 0;    
}

output ./a.out

5 6 7
3 6 10
5 6 7 3 6 10

Is there a better way to do same?

  • What is the criteria? You will enter space separated numbers in 2 lines and yu have to input and store it in array? – user2736738 Feb 01 '18 at 11:03
  • unlimited `do while` with array size 3, best of luck. :) – Sourav Ghosh Feb 01 '18 at 11:03
  • @coderredoc yes the criteria is just to enter array elements with space seperation. Enter next array after enter is pressed. – pointer accurate Feb 01 '18 at 11:05
  • @pointeraccurate.: What about entering 1000 numbers when the array can contain only 3 elements? – user2736738 Feb 01 '18 at 11:06
  • @coderredoc That is a simple problem. The more simpler problem is entering array elements with space and ending with \n.Is there any scanf way to do it in one line? – pointer accurate Feb 01 '18 at 11:09
  • I conclude there is no way. These are the things I don't wanted as an answer.I need to do it the hard way then. – pointer accurate Feb 01 '18 at 11:12
  • regarding: `scanf("%d%c", &alc[i], &temp);` the '%d' input format specifier will consume/discard an leading 'white space', so no need for the '%c' and related 'temp' variable – user3629249 Feb 02 '18 at 06:37
  • for ease of readability and understanding: 1) consistently indent the code, Indent after every opening brace '{'. Unindent before every closing brace '}'. Strongly suggest each indent level be 4 spaces. – user3629249 Feb 02 '18 at 06:39
  • 1
    when calling any of the `scanf()` family of functions, always check the returned value (not the parameter values) to assure the operation was successful. In the current scenario, any returned value other than 2 indicates an error. Note: scanf() does not set `errno` when some input format specifier fails, so should use `fprintf( stderr, "...\n" )` rather than `perror()` when reporting the error. – user3629249 Feb 02 '18 at 06:42

3 Answers3

2

The idea is get the line as input and then parse it to get the integers using strtol etc. The line you will get using fgets. And then you will store it in array. There are two options now,

  • If you get more elements than you can hold in the array then you will show error when the array is full.

  • Or use dynamically allocated memory which will grow as the number you enter increase.

I am afraid, using scanf until you get integers is an option - but that is not the good idea and scanf is not the easy way to go about this.

user2736738
  • 30,591
  • 5
  • 42
  • 56
  • @pointeraccurate.: You haven't even run the above code in other answer- do you think it's correct? Why don't you run the code then! – user2736738 Feb 02 '18 at 09:35
  • I have yet to do that. I will change the acceptance once I go through fully this whitespace thing and scanf and convince myself that doing it with scanf is always going to create newer corner cases. Right now I am doing another problem and I will come again for this problem in some time. – pointer accurate Feb 02 '18 at 11:09
  • The real answer for my confusion is here. https://stackoverflow.com/questions/9599794/putting-numbers-separated-by-a-space-into-an-array You had already posted that link too. The gist of that answer you already have posted here. for more robustness linked answer is sufficient. – pointer accurate Feb 02 '18 at 13:13
  • Just posted my changed program as an answer. – pointer accurate Feb 02 '18 at 13:32
1

the following proposed code:

  1. cleanly compiles
  2. follows the axiom: only one statement per line and (at most) one variable declaration per statement.
  3. is consistently indented
  4. eliminates unneeded variables
  5. limits the scope of variables
  6. performs the desired functionality
  7. properly checks for error indications from system functions
  8. documents why each header file was included
  9. all 'magic' numbers given meaningful names (via #define statement)

and now the proposed code:

#include <stdio.h>     // scanf(), fprintf(), stderr, printf()
#include <stdlib.h>    // exit(), EXIT_FAILURE


#define MAX_NUMS_PER_PERSON 3


int main( void )
{
    int alice[ MAX_NUMS_PER_PERSON ]={0};
    int bob[ MAX_NUMS_PER_PERSON ]={0};

    //enter alice
    for( int i=0; i< MAX_NUMS_PER_PERSON; i++ )
    {
        if( 1 != scanf("%d", &alice[i]) )
        {
            fprintf( stderr, "failed to input nums for Alice\n" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf successful
    }

    //enter bob
    for( int i=0; i< MAX_NUMS_PER_PERSON; i++ )
    {
        if( 1 != scanf("%d", &bob[i]) )
        {
            fprintf( stderr, "failed to input nums for Bob\n" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf successful
    }


    //print alice
    for( int i = 0; i < MAX_NUMS_PER_PERSON; i++)
    {
        printf("%d ", alice[i]);
    }

    //print bob
    for( int i = 0; i < MAX_NUMS_PER_PERSON; i++)
    {
        printf("%d ", bob[i]);
    }

    return 0;
}
user3629249
  • 16,402
  • 1
  • 16
  • 17
0

Changed my C program according to this answer

Putting numbers separated by a space into an array

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

#define ARRAY_SIZE 3

#define BOB_SIZE    5
#define ALICE_SIZE  4

int main()
{
    int tmp, i=0;
    char follow;
    int count;
    int a[ALICE_SIZE]={0}, b[BOB_SIZE]={0};

    if((ALICE_SIZE < ARRAY_SIZE) || (BOB_SIZE < ARRAY_SIZE))
    {   
        printf("Not sufficient space in array, check the sizes.\n");
        return -1;
    } 

    while ((i < ARRAY_SIZE) && (count = scanf("%d%c", &tmp, &follow)) > 0)
    {
      if ((count == 2 && isspace(follow)) || (count == 1))
      {
        a[i++] = tmp;
      }
      else
      {
        printf ("Bad character detected: %c\n", follow);
        break;
      }
    }

    i=0;

    while ((i < ARRAY_SIZE) && (count = scanf("%d%c", &tmp, &follow)) > 0)
    {
      if ((count == 2 && isspace(follow)) || (count == 1))
      {
        b[i++] = tmp;
      }
      else
      {
        printf ("Bad character detected: %c\n", follow);
        break;
      }
    }

    for(i = 0; i < ARRAY_SIZE ; i++)
        printf("%d ", a[i]);

    printf("\n");
    for(i = 0; i < ARRAY_SIZE ; i++)
        printf("%d ", b[i]);

    return 0;
}

Tried to make input as general as possible while using scanf looks like too much effort but its required to make it robust,and put corner cases and errors.

More problems with scanf comes with strings or %s specifier. So better get used to fgets, strtol and dynamic arrays in parsing while giving inputs.