开发者

Why does not the input of a string work?

#include <stdio.h>
int main()
{
        char temp[1024];
        if(getchar() != 'y')
        {
                printf("no options\n");
                return 1;
        }
        scanf(temp, "%s");
     开发者_如何转开发   printf("%s", temp);
}

I get snippet as below. I just want twice input from user. but the first input works, however the second directly skips and the printf("%s", temp); printed unexpected characters. How can I resolve the problem.. thanx


The first parameter to scanf is the format, and the second is the buffer. You have it backwards. Try scanf( "%s", temp );.


Others have already given you the actual answer, and you should accept one of those but feel free to upvote me if you like this sage advice :-)

Use of gets should never be contemplated if you're looking for a robust application. That's because there's no way to guard against a buffer overflow which could render your program insecure.

I prefer a little function like getLine() in the following program. It uses fgets which can be protected from oveflow and is a robust solution.

#include <stdio.h>
#include <string.h>

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
    int ch, extra;

    // Get line with buffer overrun protection.
    if (prmpt != NULL) {
        printf ("%s", prmpt);
        fflush (stdout);
    }
    if (fgets (buff, sz, stdin) == NULL)
        return NO_INPUT;

    // If it was too long, there'll be no newline. In that case, we flush
    // to end of line so that excess doesn't affect the next call.
    if (buff[strlen(buff)-1] != '\n') {
        extra = 0;
        while (((ch = getchar()) != '\n') && (ch != EOF))
            extra = 1;
        return (extra == 1) ? TOO_LONG : OK;
    }

    // Otherwise remove newline and give string back to caller.
    buff[strlen(buff)-1] = '\0';
    return OK;
}

 

// Test program for getLine().

int main (void) {
    int rc;
    char buff[10];

    rc = getLine ("Enter string> ", buff, sizeof(buff));
    if (rc == NO_INPUT) {
        printf ("No input\n");
        return 1;
    }

    if (rc == TOO_LONG) {
        printf ("Input too long\n");
        return 1;
    }

    printf ("OK [%s]\n", buff);

    return 0;
}

Sample runs with 'hello', CTRLD, and a string that's too big:

pax> ./qq
Enter string> hello
OK [hello]

pax> ./qq
Enter string>
No input

pax> ./qq
Enter string> dfgdfgjdjgdfhggh
Input too long

pax> _


You need to switch the parameters to scanf.

#include <cstdio>

using namespace std;

int main()
{
    char buf[100];
    while (true)
    {
        if (scanf("%s",buf) == EOF)
        {
            printf("fail");
            return 1;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜