有没有办法将 getchar() 中的值更改为 C 中的整数?

发布于 2025-01-14 01:56:30 字数 375 浏览 4 评论 0原文

我正在用 C 编写一个程序,其中它将请求响应,然后使用数字的第一次出现(使用 isdigit() ),然后将其分配给变量以供以后使用。经过一番测试后,我意识到它的 ascii 值为 10,即换行。这是代码片段。

    while(isdigit(ch) == 0){
                ch = getchar();
        }
        ch = getchar();
        star = ch;//value is being detected as 10, which is line feed.

我在将 ch 分配给 star 时尝试将其转换为 int,这并没有改变结果值 10。我的问题是在 ch 的分配中,还是语法很差?

I'm working on a program in C in which it will request a response, then use the first appearance of a digit (using isdigit() ) and then assign it to a variable for later use. After testing a bit I realized it was taking the ascii value for 10, which is line feed. Here is the code snippet.

    while(isdigit(ch) == 0){
                ch = getchar();
        }
        ch = getchar();
        star = ch;//value is being detected as 10, which is line feed.

I tried casting ch to int when assigning it to star, which did not change the resulting value of 10. Is my issue within the assignment of ch, or is it poor syntax?

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

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

发布评论

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

评论(1

坦然微笑 2025-01-21 01:56:30

你的问题是你看到一个数字,然后你读下一个字符

    while(isdigit(ch) == 0){
            ch = getchar();
    }
    ch = getchar(); <<<======

只需使用你已有的 ch 中的值,加上你需要将 '0' 转换为 0,不是同一件事

    while(isdigit(ch) == 0){
            ch = getchar();
    }
    int inp = ch - '0';

YOur problem is that you see a digit, then you read the next character

    while(isdigit(ch) == 0){
            ch = getchar();
    }
    ch = getchar(); <<<======

Just use the value in ch that you have already, plus you need to convert '0' to 0, not the same thing

    while(isdigit(ch) == 0){
            ch = getchar();
    }
    int inp = ch - '0';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文