gpt4 book ai didi

c - 在我输入负整数之前,如何让这段代码扫描一个整数序列?我以为 %u 不会取负整数

转载 作者:太空宇宙 更新时间:2023-11-04 06:55:27 25 4
gpt4 key购买 nike

我希望 while 循环在我输入未签名的数字时结束(低于零),但直到我输入一些符号才会发生在我的键盘上(字母等)然后调试停止。谁能帮忙我,好吗?

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

#define ALLOC_CHECK(p) if (!(p)) puts("Neuspesna alokacija"), exit(1)

bool is_palindrome(unsigned x)
{
unsigned i, j, n = 8 * sizeof x; // Broj bita unsigned x

for (i = 1 << n-1, j = 1; i > j; i >>= 1, j <<= 1)
if (!(x & i) != !(x & j)) // Proverava da li su biti logicki razliciti
return false;

return true;
}

int main(void)
{
unsigned size = 10, n = 0, i;
unsigned *a = malloc(size * sizeof(*a));
ALLOC_CHECK(a);

puts("Enter a sequence of integers:");
while (scanf("%u", &a[n++]))
if (n == size) {
size *= 2;
a = realloc(a, size * sizeof(*a));
ALLOC_CHECK(a);
}

// Moze i da se skrati na pravu duzinu sa a = realloc(a, n * sizeof(*a));

puts("Binary palindromes are:");
for (i = 0; i < n; i++)
if (is_palindrome(a[i]))
printf("%u ", a[i]);

free(a);
}

最佳答案

I want that while loop ends when I enter number that's not unsigned (lower than zero).

将输入视为需要测试的文本。

// input examples
"-12345678901234567890" should stop the loop
"-1" should stop the loop
"123" should be read successfully as an `unsigned`
" +123" should be read successfully as an `unsigned`
"12345678901234567890" is outside `unsigned` range and results are TBD
"abc" is not `unsigned`, so should stop loop.
"" is not `unsigned`, so should stop loop.
" 123 xyz" is not `unsigned`, so should stop loop.
etc.

使用 fgets() 更健壮,但让我们尝试使用 scanf() 解决方案。

I thought %u won't take negative integers

scanf("%u",... 将接受像 "-123" 这样的输入并将其转换为 unsigned。所以需要代码来检测 -

以下将不会检测溢出或纯空白行,也不会在 - 之后消耗文本。

// consume leading white space, look for `-` (various approaches)
int n = 0;
scanf(" -%n", &n);
if (n > 0) exit_loop(); // `-` found

unsigned x;
if (scanf("%u", &x) != 1) exit_loop(); // non numeric input
// Success, use `x`
...

在使用 "%1[-]" 寻找 -

丑陋 while 循环中
char minus[2];
// while a search for `-` failed and `unsigned` succeeded
while (scanf(" %1[-]", minus) != 1 && scanf("%u", &x) == 1) {
...
}

关于c - 在我输入负整数之前,如何让这段代码扫描一个整数序列?我以为 %u 不会取负整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45641599/

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