Simple problem with ending an array-input loop in C

Discussion in 'Programmer's Corner' started by Fraser_Integration, Dec 14, 2009.

  1. Fraser_Integration

    Thread Starter Member

    Nov 28, 2009
    142
    5
    Hello there.

    Please see the code I have written below

    void main(void)
    {
    int a[MAX];
    int i, count=0;
    printf("Enter vectors. Enter 666 to stop.\n\n");
    for(i=0;i<MAX;i++)
    {
    printf("Vector %i: ", i+1);
    scanf("%i", &a);
    count++;
    if(a == 666)
    {count--;break;}

    }

    I am attempting to input an array of integers, and stop entering those integers either with a blank line, or a word. Anything but 666! It's so tacky.

    I have tried %s in scanf and typecasting to an int, but that still does not terminate the loop when I substitute 666 for "stop" in the if statement.

    I'm sure it's something simple, any suggestions?

    Thanks,
    Fraser
     
  2. spinnaker

    AAC Fanatic!

    Oct 29, 2009
    4,887
    1,014
    Wow console! :)


    Been years since I have done all that much with it.


    There are tons onf ways to do this but this is one:

    // TestPrj.cpp : Defines the entry point for the console application.
    //

    #include "stdafx.h"
    #include <string.h>
    #include <stdlib.h>


    #define MAX 10

    void main(void)
    {
    int a[MAX];
    int i, count=0;
    char str[1000];

    printf("Enter vectors. Enter end to stop.\n\n");
    for(i=0;i<MAX;i++)
    {
    printf("Vector %i: ", i+1);

    scanf("%s", str);

    count++;

    if (strncmp(str,"end",3) == 0)
    break;
    else
    a = atoi(str);




    }


    for (i=0; i<count-1; i++)
    {

    printf("Vector %i = %i: \n", i,a);


    }
    }


    If I remember correctly you can also trap control break but I have not done that in years.


    BTW Most of the functions above have been deprecated. Note sure what compiler you were using.
     
  3. Fraser_Integration

    Thread Starter Member

    Nov 28, 2009
    142
    5
    Hi there. I looked into the atoi function as it was new to me, set up an array for a temporary string as you suggested, tried atoi and it worked first time. much obliged!
     
Loading...