-3

Before I start please keep in mind that I am still learning and need help with some stuff that may be easy to you but not to me. So here we go. I am having trouble using scanf in a custom function. It will not let me type anything. It just keeps running forever unless I stop it. How can I get scanf to work here:

#include <stdio.h>
#include <stdlib.h>

void function ();

int main (void)
{
  char sel;
  function ();
  return 0;
}

void function ()
{
  scanf("%c",&sel);
}
  • It's hard to help you without knowing what it is you're trying to do and what behavior you are seeing. – David Schwartz May 27 '16 at 23:32
  • 4
    Please explain 'trouble'. What 'trouble'? – Martin James May 27 '16 at 23:33
  • Could you give a more detailed description about how your program isn't working? What are you using to compile it? How are you compiling it with that? What happens when you run it? – amaurea May 27 '16 at 23:33
  • Just trying to help out with general coding, try not to use global variables unless they're necessary, it would be enough if it's local to main. There's no point in creating a function with only calls scanf with a global variable. – Mr. Branch May 27 '16 at 23:33
  • @jacobgarner Don't remove curly braces around loop body: http://stackoverflow.com/questions/359732/why-is-it-considered-a-bad-practice-to-omit-curly-braces?lq=1 – Barmar May 27 '16 at 23:47
  • @MartinJames it will not let me type anything in. Nor will it print if you use printf. – Jacob Garner May 28 '16 at 00:22
  • Well now you have `function()` trying to access a variable that's local to `main()`. – jamesdlin May 28 '16 at 01:00
  • When you ask questions about code, you really should copy and paste the exact code. It's also weird that you completely changed the code after you asked the question, and the accepted answer makes *no* sense with the current version. – jamesdlin Jun 05 '16 at 15:55

1 Answers1

0

There is no problem with scanf. The problem is with your loop. l = 1 and l++ will always keep l >= 0 and hence it will keep on taking input infinite times. Also, it will keep on overriding the value of var.a with every input

Priyansh Goel
  • 2,660
  • 1
  • 13
  • 37