当我在linux上使用GCC编译它时,因为我在等待输入,所以“hi”出现了。我不想使用scanf,并且想要知道为什么在我要求用户输入名称时hi正在显示。此外,当我想打印刚刚传递的文件的名称时,我得到垃圾字符。在netbeans中,我得到了我想要的东西。但在Linux上,它决定采取奇怪的行动。请帮忙
代码:
int main(int argc, char** argv)
{
char val[70];
if(write(1, "Please input your name", 36)!=36)
{
return -1;
}
if(read(0, val, 36) < 0)
{}
if(write(1, val, 36)!=36)
{}
printf("Yo");//THIS IS PRINTING OUT WAY BEFORE IT IS CALLED, ANY VARIABLE WITH A STRING GETS PRINTED OUT, EVEN WITHOUT PRINTF BEING INVOKED
}
输出:
Please input the file nameYo: hi
hi
???Om?0?a?Sm? <<WHAT IS THIS? I DONT GET THIS ON NETBEANS
答案 0 :(得分:3)
write
的第三个参数是您尝试打印的字符串的字节长度。你有36,但你提供的字符串只有22个字节长。将代码更改为如下所示将按预期运行:
int main(int argc, char** argv)
{
char val[70];
if(write(1, "Please input your name", 22)!=22)
{
return -1;
}
if(read(0, val, 36) < 0)
{}
if(write(1, val, 36)!=36)
{}
printf("Yo");//THIS IS PRINTING OUT WAY BEFORE IT IS CALLED, ANY VARIABLE WITH A STRING GETS PRINTED OUT, EVEN WITHOUT PRINTF BEING INVOKED
}
请注意,您应该考虑使用printf
和scanf
,这样您就不必担心字节长度了。
这可能是这样的:
#include <stdio.h>
int main(int argc, char** argv)
{
char val[70];
printf("Please input your name");
if(scanf("%69s", &val) == 1)
printf(val);
printf("Yo");
}