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