TIP: Click on subject to list as thread! ANSI
echo: aust_c_here
to: Keith Fowler
from: Michael Stapleton
date: 1996-08-26 02:55:00
subject: Scanf (was Libraries)

-=> Quoting Keith Fowler to Paul Edwards <=-

Hello Keith,

KF> While I'm here though, could you please tell me why this doesn't
KF> work porperly:

KF> char name[30];
KF> printf("Please Enter Name: ");
KF> scanf("%s",name);

KF> when this inputs the string, if I have a space in bewteen
KF> something (for example "Keith Fowler") it only puts
"Keith" in
KF> the name[30], then if I do another scanf it then puts "Fowler"
KF> starigh into that string....

Sorry, that's the way scanf() works - it uses white space as a
separator.  It's a tricky function to use & it can even be
dangerous.  For example, with your code above, if the user puts in a
string which is longer than 29 characters, it will overrun your
name[] array.  This may not actually hurt in some circumstances, but
in others it will cause a crash.

KF> Am I using a wrong command??, or am I using this one wrong?

Both.  :) Most programmers avoid scanf() like the plague, mainly
because of the problem I mentioned above.

Try this:

/*
 *  Fgets demo. Public domain.
 *  Tested Aug 25 1996 23:54:04
 */

#include 

#define NAMEMAX 30

int main(void)
{
    char name[NAMEMAX];

    do
    {
        printf("Please Enter Name: ");
        fgets(name, NAMEMAX, stdin);
        printf("Name = %s\n", name);
    } while (*name != '\n');

    return 0;
}

/* * * * * * * * * * * * * * * * * * * * */

In more complex cases, you can use sscanf() to parse the data one
you've read it into a large enough array.

I hope this helps,

Michael Stapleton of Graphic Bits.

 * AmyBW v2.10 *
... This tagline is encrypted
--- AdeptXBBS v1.07f (Registered)
* Origin: Mach One BBS (3:713/615)
SEEN-BY: 50/99 620/243 623/630 711/401 409 410 413 430 808 809 932 934
SEEN-BY: 712/515 713/111 317 601 611 615 618 700 826 888 914 714/906 800/1
@PATH: 713/888 711/808 934

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.