Thread: Using scanf in a for loop

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    67

    Using scanf in a for loop

    how do you make scanf read in numbers in a for loop?? this is what i want it to do:
    example input:
    45 34 67 78
    scanf terminates after space is pressed so how do i get around that problem?

    this is my code so far:
    Code:
    #include <stdio.h>
    
    void swap(int *p, int *q)
    {
        int tmp;
    	
        tmp = *p;
        *p = *q;
        *q = tmp;
    }
    
    void bubble (int a[10])
    {
    	int i, j;
    	
    	for (i = 0; i < 9; i++)
    		for (j = 9; i < j; j--)
    		if (a[j - 1] > a[j])
    			swap(&a[j - 1], &a[j]);
    }
    
    int	main (void)
    {	
    	int i;
    	int a[10];
    	for (i = 0; i < 10; i++){
    		scanf ("%d\n", &a[i]);}
    	bubble (a);
    	for (i = 0; i < 8; i++)
    	printf(" %d", a[i]);
    	printf("\n");
    	printf("\n");
    	return 0;
    }
    what should i put into the scan set for scanf to make it work? thanks

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Maybe because you are asking it to read until a newline with "%d\n", so you need to enter multiple lines, not spaces?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Just drop the \n from the scanf call.

    \n doesn't just match a single \n, it matches any sequence of any length of any white-space character.
    So the input of the 10th number will only return AFTER you type a non-whitespace character after your 10th number.
    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. scanf() consideres useless
    By Snafuist in forum C Programming
    Replies: 15
    Last Post: 02-18-2009, 08:35 AM
  2. Help with a basic scanf procedure.
    By killpoppop in forum C Programming
    Replies: 9
    Last Post: 11-03-2008, 04:39 PM
  3. Replies: 2
    Last Post: 02-20-2005, 01:48 PM
  4. Scanf and integer...
    By penny in forum C Programming
    Replies: 3
    Last Post: 04-24-2003, 06:36 AM
  5. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM