-1

Is it any possible chance to print to IO device with the help of scanf() function?

main()
{
char str[30];
scanf("\n Name ?%s",&str);

printf("\n Name Entered is %s",str);
}

Try this and help me out.

udhaya kumar
  • 63
  • 1
  • 2
  • 6

2 Answers2

6

The scanf function reads input from the console and parses it. It has no means of printing anything. That's what the aptly-named printf family of functions is for.

Joey
  • 344,408
  • 85
  • 689
  • 683
4

The first argument to scanf is not a prompt (as it looks like you're assuming), it's the format string to be used to scan the input.

That scanf will fail unless your input matches exactly what's expected including the literal string "Name ?" and so forth. It will also stop at the first whitespace so entering udhayar kumar would only get your first name. If you want a prompt simply output it beforehand such as with:

char str[30];
printf ("Name? ");
scanf ("%s", str);

printf ("Name Entered is %s\n", str);

However keep in mind that unbound %s format specifiers for scanf are an easy way to crash your program or give someone a security hole they can get through (see "buffer overflow"). That's because there's no bounds checking on the input.

If you want a decent input function, check out this one. It gets an entire line (with optional prompt) and handles error conditions well.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 1
    scanf("\n Name ?%s",&str); This actually works. Try to work with it. After running the file, type " Name ?udhay" and press enter. Now String "udhay" is assigned to var str. Check it out.... Thanx for ur respons too. – udhaya kumar Sep 16 '12 at 17:16
  • 1
    Yes, it works (for some definitions of 'work') but it constrains your input. What you see is _no_ indication that the program is waiting, and you have to enter not only your name but all that unnecessary cruft before it - that seems like a very badly designed way to get someone's name. In any case, that's _still_ not printing with `scanf` as your question asks. – paxdiablo Sep 16 '12 at 23:42