我要尝试执行的操作是要求用户以类似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 pathname
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] = '\0'
来解决此问题:
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] = '\0';
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);
}