%d和%i用作格式说明符的区别是什么printf?
为什么在阅读时scanf()需要l" %lf" double,何时printf()可以使用" %f",无论其参数是a double还是a float?
示例代码:
double d;
scanf("%lf", &d);
printf("%f", d);
Run Code Online (Sandbox Code Playgroud) 我对某些事情有点困惑.我的印象是,读取C字符串的正确方法与之scanf()相符
(不要介意可能的缓冲区溢出,这只是一个简单的例子)
char string[256];
scanf( "%s" , string );
Run Code Online (Sandbox Code Playgroud)
但是,以下似乎也有效,
scanf( "%s" , &string );
Run Code Online (Sandbox Code Playgroud)
这只是我的编译器(gcc),纯粹的运气还是别的什么?
我经常看到人们不鼓励其他人使用scanf并说有更好的选择。但是,我最终看到的只是“不要使用scanf”或“这里是正确的格式字符串”,并且从来没有提到“更好的替代方案”的任何示例。
例如,让我们看一下这段代码:
scanf("%c", &c);
Run Code Online (Sandbox Code Playgroud)
这将读取最后一次转换后留在输入流中的空白。通常建议的解决方案是使用:
scanf(" %c", &c);
Run Code Online (Sandbox Code Playgroud)
还是不使用scanf。
由于scanf不好,用于转换scanf通常无需使用即可处理的输入格式(例如整数,浮点数和字符串)的ANSI C选项有哪些scanf?
使用以下代码:
char *name = malloc(sizeof(char) + 256);
printf("What is your name? ");
scanf("%s", name);
printf("Hello %s. Nice to meet you.\n", name);
Run Code Online (Sandbox Code Playgroud)
用户可以输入他们的名字,但是当他们输入一个像空格一样的名字时Lucas Aardvark,scanf()只需切断后面的所有内容Lucas.如何设置scanf()允许空格
我有以下程序
#include <stdio.h>
int main(void)
{
unsigned short int length = 10;
printf("Enter length : ");
scanf("%u", &length);
printf("value is %u \n", length);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
其中编译时使用gcc filename.c发出以下警告(scanf()在行中).
warning: format ‘%u’ expects argument of type ‘unsigned int *’, but argument 2 has type ‘short unsigned int *’ [-Wformat]
然后我提到的C99 specification - 7.19.6 Formatted input/output functions,并使用长度调节剂(如当不明白正确的格式指定符short,long等)与unsigned用于int数据类型.
是%u正确的说明符unsigned short int吗?如果是这样,为什么我得到上述警告?!
编辑:大多数时候,我在尝试%uh,它仍在发出警告.
我正在使用Ubuntu,我也使用Geany和CodeBlock作为我的IDE.我正在尝试做的是读取一个字符串(如"Barack Obama")并将其放在一个变量中:
#include <stdio.h>
int main(void)
{
char name[100];
printf("Enter your name: ");
scanf("%s", name);
printf("Your Name is: %s", name);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Enter your name: Barack Obama
Your Name is: Barack
Run Code Online (Sandbox Code Playgroud)
如何让程序读取整个名称?
在C:我正在尝试从用户获取char scanf,当我运行它时程序不等待用户输入任何东西......
这是代码:
char ch;
printf("Enter one char");
scanf("%c", &ch);
printf("%c\n",ch);
Run Code Online (Sandbox Code Playgroud)
为什么不工作?
我用这个代码:
while ( scanf("%s", buf) == 1 ){
Run Code Online (Sandbox Code Playgroud)
什么是防止可能的缓冲区溢出的最佳方法,以便它可以传递随机长度的字符串?
我知道我可以通过调用例如限制输入字符串:
while ( scanf("%20s", buf) == 1 ){
Run Code Online (Sandbox Code Playgroud)
但我更愿意能够处理用户输入的任何内容.或者这不能使用scanf安全地完成,我应该使用fgets?
我有以下程序:
int main(int argc, char *argv[])
{
int a, b;
char c1, c2;
printf("Enter something: ");
scanf("%d",&a); // line 1
printf("Enter other something: ");
scanf("%d", &b); // line 2
printf("Enter a char: ");
scanf("%c",&c1); // line 3
printf("Enter another char: ");
scanf("%c", &c2); // line 4
printf("Done"); // line 5
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
正如我在C书中读到的那样,作者说scanf()在缓冲区中留下了一个新的行字符,因此,程序不会在第4行停止供用户输入数据,而是将新行字符存储在c2中并移至第5行.
是对的吗?
但是,这只发生在char数据类型中吗?因为我没有int在第1,2,3行中看到数据类型的这个问题.是不是?