gpt4 book ai didi

c - 从输入中获取用户的选择

转载 作者:行者123 更新时间:2023-11-30 15:40:59 25 4
gpt4 key购买 nike

我的任务是使用两种方法获取用户的输入。

我想给用户选择。如果他想要方法 1,请按 1。否则,请按 0。

然后用户开始输入一个我必须打印的字符串。我打印输入,直到用户按下 Enter 按钮或 EOF。

问题是,当用户给我他的“选择”时,他按下回车按钮('\n'),这样我的程序就存在了。

我该如何解决这个问题?

printf("please enter your chioce: for malloc press 1. for linked list press 0\n");
scanf("%d",&n);

if (n)
printWithMalloc();

else{
.....

为了清楚起见,我的 if 输入:

printf("please enter a string. the string will be printed right away.\n");
while ((c=getchar())!=EOF && c!='\n')

最佳答案

忘记scanf()

<小时/>

如果我理解你的问题是正确的,你想在用户输入空行时退出。如果是这样,只需读取整行,并检查它是否为空(除了尾随换行符之外)字符):

while (1) {
char buf[LINE_MAX];
if (!fgets(buf, sizeof buf, stdin))
break; // EOF

if (buf[0] == '\n')
break; // empty line

// if we got here, the user entered something; try converting it to an int
int choice = strtol(buf, NULL, 0);
// and do stuff with it
}

关于c - 从输入中获取用户的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20723754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com