首页 > 解决方案 > while 循环,int vs char 从 scanf 读取,true 和 false

问题描述

#include <stdio.h>
int main()
{
    int number; // We make 1 int named number
    scanf("%d",&number); // We give to number some number xd
    while (number!=0)// We made a loop while if number isn't 0 do that
    {
        printf("text");// print text
        scanf("%d",&number); // and get again a number. 
        // So everything works well beside inserting some char instead of int.
        // So what is the problem wont scanf return 0 so we exit the program not
        // just printing a text all day?  That's my first question.
    }
    return 0;
}

第二个问题是如何让程序从键盘读取数字,直到我为 ex '.' 输入一些特殊符号。是的,我们用循环来做,对吗?但是,如果我输入除数字以外的所有内容,scanf("%d",&something)它会如何返回?0

标签: cloopscharintscanf

解决方案


将它从 scanf int 更改为 char

假设:您一次读取一个字符

#include <stdio.h>

int main()
{
    char c = "0";
    int n = 0;

    while (n != 46)// we made a loop while if char isn't '.' ASCII - 46 do that
    {
        scanf(" %c", &c);
        n = (int)c;
        printf("text %d", n);
        //Add if statement to confirm it is a number ASCII 48 - 57 and use it.
    }
    return 0;
}

编辑:关于如何使用数字的更多信息:一个接一个地输入数字,或者只输入一个整数,如 123,并带有一些结尾特殊字符,如 ';' 或换行

scanf(" %c", &c);

至:

scanf("%c", &c);

这样它会将 '\n' 注册为 ASCII 10

将其与 atoi 一起使用以获取实际的 int 值并使用它。

编辑2:

@World,您不能期望只读取数字和“。” 使用您自己的代码执行此操作的一种方法是:

#include <stdio.h>

int main()
{
    char c = "0";
    int n = 0;
    int number = 0;

    while (n != 46)// we made a loop while if char isn't '.' ASCII - 46 do that
    {
        scanf("%c", &c);
        n = (int)c;

        if (n>=48 && n<=57) {
            number *= 10;
            number += (n-48);
        }
        if (n==10) {
             printf("text %d\n", number);
             //Use number for something over here
             number = 0;
        }
    }
    return 0;
}

编辑3:这背后的逻辑:

假设您在控制台中输入 341 行

scanf("%c", &c);

将一一读取,因此在 while 循环中分别读取 '3'、'4'、'1' 和 '\n'

while (n != 46)

因此将运行 4 次,其中:

第一次

c = '3';
n = 51;
如果 (n>=48 && n<=57) 为真;
数字 = 0 * 10;
数字 = 数字 + n - 48 = 0 + 51 - 48 = 3

第二次

c = '4';
n = 52;
如果 (n>=48 && n<=57) 为真;
数字 = 3 * 10 = 30;
数字 = 数字 + n - 48 = 30 + 52 - 48 = 34

第三次

c = '1';
n = 49;
如果 (n>=48 && n<=57) 为真;
数字 = 34 * 10 = 340;
数字 = 数字 + n - 48 = 340 + 49 - 48 = 341

第四次

c = '\n';
n = 10;
如果 (n>=48 && n<=57) 为假;
如果 (n==10) 为真;
它打印“文本 341”并将数字设置为 0

当 c = '.' 时循环退出 n = 46


推荐阅读