strncpy函数无法正常工作

时间:2014-11-19 14:31:03

标签: c strncpy

我要做的是要求用户输入格式为:cd directory。然后我将“cd”存储在字符串中,将“directory”存储在另一个字符串中。这是我的代码:

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" 

那是为什么?

1 个答案:

答案 0 :(得分:1)

这是因为在执行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);
}
相关问题