c - 从最大大小为 100 的数组中获取用户输入后,如何检查用户输入了多少个值?

标签 c arrays scanf

<分区>

我对数组的最大大小(N)有限制,我想要求用户输入一个可以小于或等于 N 的数字数组。我如何找到用户有多少个值输入了吗?

这就是我所拥有的,但它不起作用。

(基本上,我告诉程序在用户按下回车键后停止计算“n”)(当然我初始化了 n=0)

for(i=0;i<(N-1);i++)
{

    scanf("%d",&a[i]);
    n++;

    if(a[i]=='/n'){break;}
}

感谢任何帮助!谢谢!

最佳答案

这不起作用,因为带有 "%d" 说明符的 scanf 将跳过 \n,您可以消耗所有白色空格字符,用fgetc()搜索'\n',可以返回最后一个不是'\n'的空白字符使用 ungetc() 到流,所以这个程序可能会做你需要的

#include <stdio.h>
#include <ctype.h>

int main()
{
    int a[100];
    int i;
    int result;

    result = 1;
    i      = 0;
    while ((i < 100) && (result == 1))
    {
        int chr;

        /* 
         * consume all whitespace characters left by previous scanf, 
         * stop if one of them is '\n' 
         */
        while (isspace((chr = fgetc(stdin))) && (chr != '\n'));
        /* found the '\n', set the flag to exit the loop */
        if (chr == '\n')
            result = -1;
        else
        {
            /* not interesting put back this character for scanf to read it */
            ungetc(chr, stdin);
            /* save the result of scanf, that way you can validate input */
            result = scanf("%d", &a[i]);
            if (result == 1)
                i++;
        }
    }
    printf("read %d numbers\n", i);

    /* print the carachters, this will print in reverse obviously */
    while (--i >= 0)
        printf("%d\n", a[i]);


    return 0;
}

关于c - 从最大大小为 100 的数组中获取用户输入后,如何检查用户输入了多少个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27948613/

相关文章:

c - gcc objdump 程序集调试

javascript - JS - 将字符串数组按日期排序

arrays - Swift 正则表达式和分隔符

c - 阵列扫描两次?

c - 从 C 中的文件读取(可变长度)输入

c - Scanf 十六进制无符号字符

c - 如何扫描这个字符串

c++ - 如何在 ubuntu 12.04 中的 C/c++ 项目中链接库

iphone - 代码或编译器 : optimizing a IIR filter in C for the iPhone 4 and later

PHP 对同一项目进行两次多重排序