Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

c - After using fgetc(stdin) on a variable, how do I pass the input to strtol?

I have a variable where the user inputs one number. That variable is of type int because that's the return value of fgetc(stdin) and getchar(). In this case, I'm using fgetc(stdin). After the user inputs the number, I would like to convert it to an integer with strtol(), however, I get a warning about an incompatible integer to pointer conversion because of strtol()'s first argument being a const char *. Here is the code:

int option;
char *endptr;
int8_t choice;

printf("=========================================Login or Create Account=========================================

");
while(1) {
    printf("Welcome to the Bank management program! Would you like to 1. Create Account or 2. Login?
>>> ");
    fflush(stdout);
    option = fgetc(stdin);
    choice = strtol(option, &endptr, 10);

Does anyone know how to get around this?

question from:https://stackoverflow.com/questions/65948015/after-using-fgetcstdin-on-a-variable-how-do-i-pass-the-input-to-strtol

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

strtol is used to convert a "string" into long, not a single char. You just need choice = option - '0' to get the value. But you don't actually need to convert because you can directly switch on the char value

switch (option)
{
    case '1':
        // ...
        break;
    case '2':
        // ...
        break;
}

If you really want to call strtol then you must make a string

char[2] str;
str[0] = option;
str[1] = 0; // null terminator
choice = strtol(str, &endptr, 10);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...