while循环,从scanf读取int vs char,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

tianlibuaiwo 回答:while循环,从scanf读取int vs char,true和false

将其从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);

将逐个读取,因此分别读取“ 3”,“ 4”,“ 1”和“ \ n” while循环

while (n != 46)

因此将运行4次,其中:

第一次

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

第二次

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

第三次

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

第四次

c ='\ n';
n = 10;
如果(n> = 48 && n 如果(n == 10)为true;
它显示“文本341”并将数字设置为0

while循环在c ='时退出。并且n = 46

,
  

如何使程序从键盘读取数字,直到我输入前一个特殊符号“。”。

scanf("%d",&number)返回0时,会有一些非数字输入。阅读带有替代代码的非数字输入。

#include <stdio.h>

int main() {
  while (1) {
    int number;
    int scan_count = scanf("%d",&number);
    if (scan_count == EOF) break;  // End-of-file or rare input error.
    if (scan_count != 1) {
      int ch = fgetc(stdin);
      if (ch == '.') break;  // Expected non-numeric input to break the loop.
      printf("Unexpected input character '%c'\n",ch);
    } else {
      printf("Expected numeric input: %d\n",ch);
    }
  } // endwhile
  printf("Done\n");
}

更好的方法是抛弃scanf()并使用fgets()`来读取用户输入。然后处理输入的字符串。

本文链接:https://www.f2er.com/3113627.html

大家都在问