如何读取数组中int的随机数

2024-05-09

我想将空格分隔的整数读取到数组中,当我按 Enter 时,它应该在任何时间点停止读取,如何实现该程序的循环,请帮助我解决这个问题。 我已经尝试过下面的代码,但它不起作用。以及如何再次读回。

#include<stdio.h>
int main()
{
    int arr[30];
    int j=0;
    while(1)
    {
        int d;
        scanf("%d",&d);
            arr[j++]=d;
        if(d=='\n')break;
    }
   return 0;
}

提前致谢


你的问题是scanf当它查找下一个项目时,将自动跳过所有空白(空格、制表符、换行符)。您可以通过专门要求读取换行符来区分换行符和其他空格:

int main() {
    int arr[30]; // results array
    int cnt = 0; // number of results
    while (1) {
        // in the scanf format string below
        // %1[\n] asks for a 1-character string containing a newline
        char tmp[2]; // buffer for the newline
        int res = scanf("%d%1[\n]", &arr[cnt], tmp);
        if (res == 0) {
            // did not even get the integer
            // handle input error here
            break;
        }
        if (res == 1) {
            // got the integer, but no newline
            // go on to read the next integer
            ++cnt;
        }
        if (res == 2) {
            // got both the integer and newline
            // all done, drop out
            ++cnt;
            break;
        }
    }
    printf("got %d integers\n", cnt);
    return 0;
}

这种方法的问题在于,它只识别整数后面的换行符,并且会默默地跳过仅包含空格的行(并从下一行开始读取整数)。如果这是不可接受的,那么我认为最简单的解决方案是将整行读入缓冲区并解析该缓冲区中的整数:

int main() {
    int arr[30]; // results array
    int cnt = 0; // number of results
    char buf[1000]; // buffer for the whole line
    if (fgets(buf, sizeof(buf), stdin) == NULL) {
        // handle input error here
    } else {
        int pos = 0; // current position in buffer
        // in the scanf format string below
        // %n asks for number of characters used by sscanf
        int num;
        while (sscanf(buf + pos, "%d%n", &arr[cnt], &num) == 1) {
            pos += num; // advance position in buffer
            cnt += 1; // advance position in results
        }
        // check here that all of the buffer has been used
        // that is, that there was nothing else but integers on the line
    }
    printf("got %d integers\n", cnt);
    return 0;
}

另请注意,当行上的整数超过 30 个时,上述两种解决方案都会覆盖结果数组。如果某些输入行比缓冲区适合的长度长,第二种解决方案也会留下一些未读的输入行。根据您的输入来自何处,这两个问题可能都需要在实际使用代码之前解决。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何读取数组中int的随机数 的相关文章

随机推荐

  • Rust 中为什么有 mod 关键字?

    看完之后this https doc rust lang org book crates and modules html 我想知道为什么有一个mod关键字和mod rs 我假设目录层次结构也可以描述模块 必须显式声明模块有几个原因 模块可
  • XAML - 将单元格的行和列索引绑定到自动化 ID

    我正在为 WPF 数据网格中的各个单元格提供自动化 ID 但遇到了一些障碍 我决定尝试根据单元格在网格中的位置 行索引和列索引 来命名单元格 使用 UI 检查器并突出显示有问题的 DataGridCell 之一会显示以下属性 GridIte
  • 如何获取当前/活动 TFS 用户的列表?

    我可以使用 TFSCONFIG IDENTITIES 查看 TFS 中的所有用户 但是 这会调出已有多年历史且不再与 AD 帐户绑定的帐户 我想将搜索限制为仅拥有 AD 帐户的用户 这可能吗 我确实在下面找到了博客 但在尝试之前 我想看看是
  • WaitForSingleObject 是否充当内存屏障?

    昨天一个关于双重检查锁定的问题引发了一系列的想法 让我对一个简单的情况感到不确定 在下面的代码中 是否可以点击printf 不再同步 在这个简单的示例中 这些值可能位于同一缓存行上 因此我认为这种可能性较小 假设一开始可能性 gt 0 如果
  • Liquibase 从 JPA 实体生成变更日志

    我有一个 Spring boot spring data jpa 项目 带有一个父模块和三个子模块 我的模块之一负责我的 JPA 实体 我需要使用该实体的 liquibase 生成一个 xml 变更日志 在我的 liquibase prop
  • 需要 python 接口将机器移动到另一个文件夹

    我正在尝试寻找代码支持python为了在数据中心的文件夹之间移动机器但没有成功 我看到pysphere您可以在克隆阶段定义文件夹 而不是在机器克隆之后定义文件夹 This https jackiechen org 2011 11 01 mo
  • Android Activity 和 Service 关系 - 暂停后、停止后

    假设创建了 Activity A 然后 A 启动了一个 Service S 并将其自身绑定到 S S 通知 A 更新 这将导致 A 的状态发生变化 Android 暂停或停止 A 后 A 和 S 会发生什么 例如 暂停 A 是否会自动解除它
  • 在android中以编程方式创建布局 - 问题

    我正在使用以下代码动态创建 FrameLayout mylayout java FrameLayout layout new FrameLayout this FrameLayout LayoutParams layoutparams ne
  • 添加UITabBarController并且没有NavigationController

    由于我是 Xamarin IOS 的新手 我想问一个问题 我已经关注了这个例子 https developer xamarin com guides ios user interface controls creating tabbed a
  • 在 GTK+ (gtkD) 中处理按键

    我正在玩gtkD http www dsource org projects gtkd GTK 的 D 绑定 我有一个window对象 实例gtk MainWindow 我想处理它的按键 How 如何处理特殊键 例如箭头键 pgup pgd
  • 如何使用 Twitter Api 在单个请求中获取 20 多个列表成员?

    我想让超过 20 个用户在单个请求中使用 twitter api 有什么参数可以指定吗 我正在使用这个APIhttp api twitter com 1 Barelyme Politics members xml cursor 1 http
  • 具有自定义尺寸的线性渐变

    我有这样的设计 它已经用 html css 创建 但我需要删除 1 和 5 的额外线条 这是通过添加绝对位置元素来创建灰线来实现的 但容器点的大小是响应式的 我的想法是为每个容器创建一个背景线性渐变 如下所示 for all backgro
  • Spotify 中的 Facebook 个人资料图片

    我想在我的 Spotify 应用程序中显示 Facebook 个人资料图片 但我应该在清单文件中允许哪些 URL 我知道我可以通过 http graph facebook com user id picture 检索图像 但这只是到实际图像
  • PHP DOM 获取节点值 html? (不剥离标签)

    我正在尝试使用nodeValue获取文件中div标签的innerhtml 但是此代码仅输出纯文本 并且似乎从div内部删除了所有html标签 我如何更改此代码以输出 div 的 HTML 内容而不是纯文本 并且还输出包装其子元素的主 div
  • CodeIgniter Active Record - 组 OR 语句

    这是我的问题 MySQL 或 条件 https stackoverflow com questions 8604380 mysql or condition 解决方案是将 OR 语句分组 但我正在使用 CodeIgniters Active
  • 上传统一块的正确顺序是什么?

    在示例页面中https www lighthouse3d com tutorials glsl tutorial uniform b locks https www lighthouse3d com tutorials glsl tutor
  • PHP:从 array_values() 内的值中去除标签

    我想在用选项卡爆炸之前将标签从 array values 内的值中剥离出来 我尝试使用下面的这一行 但出现错误 output implode t strip tags array keys item 理想情况下 我想从值中去掉换行符 双空格
  • 无法解析配置“:app:debugRuntimeClasspath”的所有文件。问题

    我的 android studio 遇到了下一个问题 导致 org gradle api internal artifacts ivyservice DefaultLenientConfiguration ArtifactResolveEx
  • 如何在Scala中实现尾递归快速排序

    我写了一个递归版本 def quickSort T xs List T p T T gt Boolean List T xs match case Nil gt Nil case gt val x xs head val left righ
  • 如何读取数组中int的随机数

    我想将空格分隔的整数读取到数组中 当我按 Enter 时 它应该在任何时间点停止读取 如何实现该程序的循环 请帮助我解决这个问题 我已经尝试过下面的代码 但它不起作用 以及如何再次读回 include