① c语言怎么解决scanf()把回车作为输入值的问题
scanf()是不会把回车拷贝到字符窜里面的。
这里是一段英文定义:the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- seeisspace).
除了回车,空格也不会拷贝到字符窜中。
再来看下gets(),英文定义是这样的:Reads characters from thestandard input(stdin) and stores them as a C string intostruntil a newline character or theend-of-fileis reached.The newline character, if found, is not copied intostr.
好了。这里写的很清楚了。gets()虽然可以把输入都拷贝到字符窜里,比如空格,但是不包含回车。
如果需要回车,可以用fgets()。英文是这样定义的:Reads characters fromstreamand stores them as a C string intostruntil (num-1) characters have been read or either a newline or theend-of-fileis reached, whichever happens first. A newline character makesfgetsstop reading, but it is considered a valid character by the function and included in the string copied tostr.
最后一句话说了,回车作为结束,不过会拷贝到字符窜中。
那么文档说的对不对呢?写一段代码测试一下。
#include<stdio.h>
intmain()
{
inti=0;
printf("scanf... ");
charscanf_content[256]={0};
scanf("%s",scanf_content);
printf("value:%s ",scanf_content);
while(scanf_content[i])
{
if(scanf_content[i]==' ')
printf("\n");
else
printf("%d ",(int)scanf_content[i]);
++i;
}
i=0;
printf("gets... ");
chargets_content[256]={0};
gets(gets_content);//unsafe
printf("value:%s ",gets_content);
while(gets_content[i])
{
if(gets_content[i]==' ')
printf("\n");
else
printf("%d ",(int)gets_content[i]);
++i;
}
i=0;
printf("fgets... ");
charfgets_content[256]={0};
fgets(fgets_content,256,stdin);
printf("value:%s ",fgets_content);
while(fgets_content[i])
{
if(fgets_content[i]==' ')
printf("\n");
else
printf("%d ",(int)fgets_content[i]);
++i;
}
return0;
}
输入“123 123”,你会发现scanf只会得到123,而gets可以得到空格123。最后fgets可以得到' '。这里为了看到空格和回车,可以把字符窜转成int打印出来。
最后的结论就是,如果需要回车,就使用fgets。
② c语言如何做到输入回车换行而不是输出结果
拍入Enter健时, c语言 通常 略去 回车,而只取用 换行键。
一定要输入 回车,你可以用输入 ASCII 值 13 代替。
例如,你拍入数值13和Enter健,用下面程序,则 s[0] 读到回车,s[1]读到换行 :
char s[10];
scanf("%d",&s[0]);
s[1]=getchar();
printf("%c %c\n",s[0],s[1]);
printf("%02x %02x",s[0],s[1]); // 输出它们的16进制ASCII码值 0d 0a
③ C语言如何做到回车停止输入
1、打开软件,直接使用int类型来定义一个变量用于保存getchar()返回的字符类型。
④ c语言如何做到输入回车换行而不是输出结果
代码可以这样写:
#include <stdio.h>
int main()
{
char s[2][128];
int i,a,b,c,d;
for(i=0;i<2;i++)
{
scanf("%d%d%d%d",&a,&b,&c,&d);
sprintf(s[i],"%d+%d+%d+%d=%d",a,b,c,d,a+b+c+d);
}
for(i=0;i<2;i++)
printf("%s ",s[i]);
return 0;
}
这是运行截图:
⑤ c语言回车是什么字符
回车符(carriage return,’ ’)。
例:
int main()
{
char ch;
ch = getchar();
printf("%d ", ch);
}
输出结果:
(5)c语言输入回车怎么办扩展阅读:
注意事项
在Windows系统中回车键被当做 的组合来使用,当从键盘输入回车键时,Windows系统会把回车键当做 来处理(只不过上面的四种字符输入函数读取的结果不同)。
getchar——换行符' '(ASCII值为10)
getch——回车符' '(ASCII值为13)
getche——回车符' '(ASCII值为13)
scanf——换行符' '(ASCII值为10)
回车:使光标移到行首
换行:使光标移到下一行
⑥ c语言怎么解决scanf()把回车作为输入值的问题,请仔细看我的代码
你的问题在于空格。
如果scanf里面有空格(你当前代码),那么输入也要加上空格:6
+
5回车
如果按照你的输入,那么scanf里面格式化字符串之间的空格要去掉。
⑦ 请问 C语言中回车键应该怎样输入
如果要在程序中表示回车键,只要用转义字符'\n'就可以了。
例如,执行输出语句
printf("Hello!\nToday
is
Friday!\n");
后,就可以得到二行内容:
Hello!
Today
is
Friday!