Function definition problem with scanf()

This is a discussion on Function definition problem with scanf() within the C Programming forums, part of the General Programming Boards category; Hello once more, I suspect that I may be again overlooking something simple, but for some reason my code is ...

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    15

    Function definition problem with scanf()

    Hello once more,

    I suspect that I may be again overlooking something simple, but for some reason my code is outputting gibberish when it should be simply using a function to take two arguments (a char and an int) and printing the char to the same value of the int, e.g. entering 'a' and '5' should produce "aaaaa".
    Code:
    #include <stdio.h>
    
    void char_times_int(char ch, int num);
    
    int main(void)
    {
        int num;
        char ch;
        
        printf("Enter a number, then a character.\n");
        scanf("%d %c", &num, ch);
        
        char_times_int(ch, num);
        
        getchar();
        getchar();
        
        return 0;
    }
    
    void char_times_int(char ch, int num)
    {
         int count;
         
         for (count = 1; count <= num; count++)
         putchar(ch);
    }
    If I remove the printf/scanf and simply define num = 5 and ch = 'a' then it works fine, but the iteration requires user input.
    Any help much appreciated whilst I hang my head in shame.

    Cheers,

    Twazzler
    Last edited by twazzler; 04-15-2011 at 11:54 AM. Reason: typo

  2. #2
    Registered User
    Join Date
    Mar 2011
    Posts
    261
    Code:
    scanf("%d %c", &num, ch);
    Look carefully...

  3. #3
    Registered User
    Join Date
    Apr 2011
    Posts
    15
    oh lawd...facepalm

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. function definition problem
    By cnu_sree in forum C Programming
    Replies: 2
    Last Post: 10-25-2007, 03:37 AM
  2. problem of class definition and main function
    By Roy01 in forum C++ Programming
    Replies: 3
    Last Post: 11-19-2006, 09:42 PM
  3. HELP!! Function Definition problem? Syntax Error I think..
    By felixgun in forum C++ Programming
    Replies: 12
    Last Post: 11-04-2006, 03:49 AM
  4. function definition(?) problem
    By Draco in forum C Programming
    Replies: 10
    Last Post: 08-06-2004, 05:48 PM
  5. lvale problem in function definition/
    By o0o in forum C++ Programming
    Replies: 8
    Last Post: 01-14-2004, 07:15 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21