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?

9
  • What is the criteria? You will enter space separated numbers in 2 lines and yu have to input and store it in array? Commented Feb 1, 2018 at 11:03
  • unlimited do while with array size 3, best of luck. :) Commented Feb 1, 2018 at 11:03
  • @coderredoc yes the criteria is just to enter array elements with space seperation. Enter next array after enter is pressed. Commented Feb 1, 2018 at 11:05
  • @pointeraccurate.: What about entering 1000 numbers when the array can contain only 3 elements? Commented Feb 1, 2018 at 11:06
  • 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. Commented Feb 2, 2018 at 6:42

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@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!
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.
The real answer for my confusion is here. stackoverflow.com/questions/9599794/… You had already posted that link too. The gist of that answer you already have posted here. for more robustness linked answer is sufficient.
Just posted my changed program as an answer.
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;
}

1 Comment

Really useful answer with points to be seriously consider always. I will try to follow the convention given in above points.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.