gpt4 book ai didi

c - C 中的格式化字符串输入和错误

转载 作者:行者123 更新时间:2023-11-30 14:55:42 25 4
gpt4 key购买 nike

struct account {
float interestRate;
char accountType[21];
};

void writeAccounts() {
struct account Acc;
FILE *fp = fopen("test.txt", "a");

printf("New interestRate : ");
scanf("%f", &Acc.interestRate);
printf("New accountType : ");
scanf("%*c%20[^\n]", Acc.accountType);

fprintf(fp, "%.2f %s\n", Acc.interestRate, Acc.accountType);

fclose(fp);
}

int main() {
int select = 0;

do {
scanf("%d", &select);
switch (select) {
case 1:
displayAccounts();
break;
case 2:
getRecNo();
break;
case 3:
writeAccounts();
break;
}
} while (select != 0);

return 0

以上是我的C代码(删除了一些不相关的函数)。当我尝试在“writeAccounts”函数中为 accountType 输入超过 20 个字符的字符串时,程序开始跳过几个步骤,直到保存我输入的所有字符。(不能使用 FGETS!我的教授不允许:/)

http://imgur.com/a/eKQRu

  1. 为什么会发生这种情况?
  2. %20[^\n] 不是意味着即使用户输入更多字符,它也只接受 20 个字符吗?
  3. 可能的方法来防止这种情况发生?

最佳答案

  1. why is this happening?

多余的输入保留在输入缓冲区中,并由后续的 scanf 调用读取。

  1. isn't %20[^\n] means its only going to accept 20 characters even if user puts more?

这是正确的,正如前面提到的,任何剩余的输入都不会被处理。

  1. possible way to prevent this ?

成功扫描后(20 个字符或更少),换行符保留在输入缓冲区中。你可以做各种各样的事情。

首先,您可以检查下一个输入字符是否是预期的换行符:

if (getchar() != '\n') {
// add code here to report the error and take evasive action
}

或者您可以通过清除缓冲区来简单地截断并忽略任何多余的输入:

int c;
while ((c = getchar()) != '\n' && c != EOF) {
// eats up the input buffer, the code is in the loop control
}

关于c - C 中的格式化字符串输入和错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45619066/

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