我试图做的是要求用户输入以下格式的内容:CD目录。然后我将"cd"存储在一个字符串中,将"目录"存储在另一个字符串中。这是我的代码:
void main()
{
char buf[50], cdstr[2], dirstr[50];
printf("Enter something: ");
fgets(buf, sizeof(buf), stdin);
//store cd in cdstr
strncpy(cdstr, buf, 2);
printf("cdstr: %s(test chars)n", cdstr);
//store directory in dirstr
strncpy(dirstr, buf+3, sizeof(buf)-3);
printf("dirstr: %s(test chars)n", dirstr);
}
输出如下,输入:cd 路径名
cdstr: cdcd pathname //incorrect answer
(test chars) //an extra "n"
dirstr: pathname //correct answer
(test chars) //an extra "n"
这是为什么?
这是因为在执行strncpy(cdstr, buf, 2)
后,cdstr
char
数组中没有以 NULL 结尾的字符串。您可以通过将cdstr
长度更改为 3 并添加: cdstr[2] = ' '
来修复它:
void main()
{
char buf[50], cdstr[3], dirstr[50]={0};
printf("Enter something: ");
fgets(buf, sizeof(buf), stdin);
//store cd in cdstr
strncpy(cdstr, buf, 2);
cdstr[2] = ' ';
printf("cdstr: %s(test chars)n", cdstr);
//store directory in dirstr
strncpy(dirstr, buf+3, sizeof(buf)-3);
printf("dirstr: %s(test chars)n", dirstr);
}