space 到底如何与 scanf 配合使用?

发布于 2024-12-28 09:49:03 字数 1061 浏览 3 评论 0原文

我是一名数学学生,正在学习 C 语言编程的基础知识。我需要一个程序来读取由数组组成的输入,该数组的组成部分必须具有某些先决条件;我希望程序询问用户数组的组成部分。然后,用户必须输入这些组件,并用空格分隔它们。对于理解主要问题而言,细节并不重要;重要的是。我将选择一个比我正在处理的更简单的示例:假设我想要一个包含 6 个组件的数组,不包含数字 4。所以我尝试:

#include <stdio.h>

int main(void) {
    int a[6];
    printf("enter components: ");
    int i;
    for (i = 0; i < 6; i++) {
        scanf("%d", &a[i]);
        if (a[i] == 4) printf(" \n\n4 is not allowed, try again\n\n");
    }
    for (i = 0; i < 6; i++) {
        printf("%d ", a[i]);
    }
}

如果我编译并运行它,例如输入:

1 2 3 4 5 6

我将收到我的错误消息,但只有在按 Enter 键后,即输入所有六个组件后(不是在第四次按空格键后立即)。所以这是我的问题(我正在寻找不使用字符串或指针的解决方案,除非没有它们就不可能做到):

  1. 有没有办法获取程序输入后续空间后立即读取组件(并采取相应行动)?我猜没有,因为 scanf 仅在用户按下 Enter 键后才起作用,而不是空格,对吗?

  2. 如果没有,有没有办法让程序在最后按回车键后立即读取所有组件,但让用户从最后一个正确的组件中选取?例如,使用上面的输入,我希望程序显示如下内容:

    4 不允许
    1 2 3 _
    

    以便用户可以更正他/她的输入(也可能更改前三位数字)。

抱歉,如果这个问题太愚蠢了!感谢您的帮助!!


编辑:嗯,感谢您的精彩回答,你们都非常有帮助!可惜我不能接受超过一个。

I am a math student, and I'm learning the very basics in programming in C. I need a program to read an input consisting in an array, the components of which must have certain requisites; I would like the program to ask the user for the components of the array. The user should then have to enter such components separating them with spaces. The details aren't important to get the main question across; I'll choose a simpler example then the one I am dealing with: let's say I want an array with 6 components not to contain the number 4. So I tried:

#include <stdio.h>

int main(void) {
    int a[6];
    printf("enter components: ");
    int i;
    for (i = 0; i < 6; i++) {
        scanf("%d", &a[i]);
        if (a[i] == 4) printf(" \n\n4 is not allowed, try again\n\n");
    }
    for (i = 0; i < 6; i++) {
        printf("%d ", a[i]);
    }
}

If I compile this and run it, and for example enter:

1 2 3 4 5 6

I will get my error message, but only after having pressed enter, that is after having entered all six components (not straight after having pressed space for the fourth time). So here are my questions (I am looking for solutions which don't make use of strings or pointers, unless it is impossible to do without them):

  1. Is there a way to get the program to read a component (and to act accordingly) straight after its subsequent space has been entered? I'm guessing there isn't because scanf only works after the user presses enter, and not space, correct?

  2. If there isn't, is there a way to get the program to read the components all at once after having pressed enter at the end, but letting the user pick up from the last right component? For example, with the above input, I would like the program to display something like this:

    4 is not allowed
    1 2 3 _
    

    so that the user can correct his/her input (possibly changing the first three digits as well).

Sorry if this question is too dumb! Thank you for your help!!


EDIT: Well, thanks for the great answers, you have all been very helpful! It's a pity I can't accept more than one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

烟火散人牵绊 2025-01-04 09:49:03

在for循环中,每次迭代后,计数器自动加一。如果你得到无效的输入,你应该阻止计数器增加。为此,只需在提供无效输入时将 i--; 添加到代码中即可。

#include <stdio.h>

int main(void) {
    int a[6];
    printf("enter components: ");
    int i;
    for (i = 0; i < 6; i++) {
        scanf("%d", &a[i]);
        if (a[i] == 4){
           printf(" \n\n4 is not allowed, try again\n\n");
           i--;
        }
    }
    for (i = 0; i < 6; i++) {
        printf("%d ", a[i]);
    }
}

In for loop, after each iteration, the counter add by one automatically. If you get an invalid input, you should prevent the counter increasing. To do this, just add i--; to your code when you give an invalid input.

#include <stdio.h>

int main(void) {
    int a[6];
    printf("enter components: ");
    int i;
    for (i = 0; i < 6; i++) {
        scanf("%d", &a[i]);
        if (a[i] == 4){
           printf(" \n\n4 is not allowed, try again\n\n");
           i--;
        }
    }
    for (i = 0; i < 6; i++) {
        printf("%d ", a[i]);
    }
}
野生奥特曼 2025-01-04 09:49:03

请看下面的代码:

#include <stdio.h>

int main(void) {
    int a[6];
    int i;
    bool hasError = false;
    int errorIndex = 0;
    do{
        hasError = false;
        printf("enter components: ");
        for (i = 0; i < errorIndex; i++)
            printf("%d ", a[i]);

        for (i = errorIndex; i < 6; i++) {
            scanf("%d", &a[i]);
            if (a[i] == 4 && hasError == false){
                printf(" \n\n4 is not allowed, try again\n\n");
                hasError = true;
                errorIndex = i;
            }
        }
    }while(hasError == true);
    for (i = 0; i < 6; i++) {
        printf("%d ", a[i]);
    }
}

Please see the bellow code:

#include <stdio.h>

int main(void) {
    int a[6];
    int i;
    bool hasError = false;
    int errorIndex = 0;
    do{
        hasError = false;
        printf("enter components: ");
        for (i = 0; i < errorIndex; i++)
            printf("%d ", a[i]);

        for (i = errorIndex; i < 6; i++) {
            scanf("%d", &a[i]);
            if (a[i] == 4 && hasError == false){
                printf(" \n\n4 is not allowed, try again\n\n");
                hasError = true;
                errorIndex = i;
            }
        }
    }while(hasError == true);
    for (i = 0; i < 6; i++) {
        printf("%d ", a[i]);
    }
}
故事与诗 2025-01-04 09:49:03

这与您的终端处于“煮熟”模式有关。在用户按下 Enter 键之前,字符甚至不会发送到程序。

This is related to your terminal being in "cooked" mode. Characters aren't even sent to the program until the user presses enter.

土豪 2025-01-04 09:49:03

您可以这样做:

int i,a[6];
for (int i=0;i<6;i++) {
 scan: scanf("%d",&a[i]);
}
for (int i=0;i<6;i++) if (a[i]==4) {
 printf("4 is not allowed. re-enter the last %d numbers\n",6-i);
 goto scan;
}

请注意,在大多数情况下,最好避免使用 goto,但在这种情况下,我认为这是自然的。

如果您确实愿意,可以打印前 i 数字(在 goto 之前),但让用户更改这些数字很复杂(并且取决于平台)。

You could do something like this:

int i,a[6];
for (int i=0;i<6;i++) {
 scan: scanf("%d",&a[i]);
}
for (int i=0;i<6;i++) if (a[i]==4) {
 printf("4 is not allowed. re-enter the last %d numbers\n",6-i);
 goto scan;
}

note that in most case, it's better to avoid using goto, but in this case I think that it's natural.

If you really want, you can print the first i numbers (before the goto), but it's complicated (and platform-depended) to let the user change those numbers.

网白 2025-01-04 09:49:03

改进 Mir Milad Hosseiny 的答案(我错误地将其识别为失控的无限循环...它实际上正是我在评论中描述的无限循环)...

我会编写一个小函数,它具有“白名单” “(您想要的东西)或“黑名单”您不想要的东西,并检查每个值是否属于(取决于方法)列表。这样你就可以保留一个单独的位置来存储你愿意接受的值或你不愿意接受的值,这样你的主要函数就不会因为“if”中的异常或包含而变得非常混乱,

所以你的代码将是

if(isAllowed(a[i]){
   myList[j] = a[i]; //j is your alternate counter
}

Improving on Mir Milad Hosseiny answer (I wrongly identified it as being an out of control infinite loop... it's actually exactly the infinite loop I describe in my comment)...

I would write a small function that has either a "white list" (things you want) or a "black list" things you don't want, and check each value to either belong or not (depending on the approach) to the list. That way you can keep a separate place where your store the values that you are willing to accept or the values you are not, so your primary function doesn't get really messy with exceptions or inclusions in the "if"

so your code would be

if(isAllowed(a[i]){
   myList[j] = a[i]; //j is your alternate counter
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文