拜托,为什么我运行该代码时打印出一个额外的“ n”?

时间:2019-10-04 16:34:50

标签: c

我正在尝试使用此代码获取pid。但是当我运行编译后的代码时。我收到一条错误消息“警告:格式指定类型为'unsigned long',但参数的类型为'pid_t'(aka'int')[-Wformat]”。

当我将格式说明符更改为仅“%lu”时,它打印时没有多余的字符。

function fetchData($url){
    $ch = curl_init();
    curl_setopt_array($ch, array(

         CURLOPT_URL            => $url,
         CURLOPT_RETURNTRANSFER => true,
         CURLOPT_SSL_VERIFYPEER => false,
         CURLOPT_SSL_VERIFYHOST => 2

        ));

          $total_result = curl_exec($ch);
          curl_close($ch);

         return $total_result;

}

function passer($id, $token)
{
   $insta_info = fetchData("https://api.instagram.com/v1/users/".$id."/media/recent/?access_token=".$token." ");

   $new = json_decode($insta_info, true);

  print_r($new);//data to printout

}

 //At this moment client_id, client_secret and other important stuff already define inside the script. 
 //I skip those lines of code which is not necessary.
 passer($data['user']['id'], $data['access_token']); //function calling and providing param
 //ex: $data['user']['id'] is 47xx493
 //ex: $data['access_token'] is random 79ea07xxxx0547a2a4b62263e68e4e8c

我期望pid为“ 60316”。我得到“ 60316n”的pid。

2 个答案:

答案 0 :(得分:0)

n打印出来的原因与p打印相同。 n不是说明符的一部分。

      vvv  --- specifier for unsigned long 
"pid: %lun"
 ^^^^^   ^ --- non-specifier characters

旁边:

pid_t数据类型是signed integer类型,能够表示进程ID

请参见What is the correct printf specifier for printing pid_t?

答案 1 :(得分:0)

您传递给printf的格式字符串是普通字符和格式说明符的混合。普通字符会自己打印,格式说明符会导致额外的参数之一被转换和打印。但是每个额外参数的类型必须与格式说明符期望的类型或多或少地完全匹配。

我们可以从警告消息中得知pidint。因此正确的格式说明符是%d

如果%lu的类型为pid,则说明符unsigned long int是正确的。

格式说明符是它们自己的小型微型编程语言。类型unsigned int的基本格式说明符是%u,您可以使用unsigned long int(字母ell)修饰符l对其进行修改以打印%lu

但是,当您编写%lun时,n实际上不是任何格式说明符的一部分,因此它是按本身打印的。

(此外,您还很幸运:尽管pid的类型和格式说明符%lu之间不匹配,但是您仍然可以打印出有意义的值。)

通常,使参数和格式说明符对齐很容易:int代表%dunsigned int代表%u%x,{{ {} {1}},long int%ld float等,但是double的正确说明符是什么,其类型为{{1 }}?今天,在您的计算机上,看来%fpid,所以pid_t是正确的,但是如果在其他计算机上使用不同的类型怎么办?您如何编写可以在任何计算机上正常工作的一段代码?一种方法是选择一个可能正确的类型,并使用该类型的说明符,然后使用显式的 cast 将您的值转换为您选择的类型。像这样:

pid_t

或者这样:

int

如果不需要强制类型转换(如果您选择的格式说明符对于计算机上的%d类型而言是正确的),则强制类型转换不会受到损害。

最后,祝贺您使用的编译器实际上向您显示警告消息:

  

警告:格式指定类型为“ unsigned long”,但参数的类型为“ pid_t”(又名“ int”)

太多的初级程序员被老版本的编译器困住了,这些老版本的编译器不输出此类警告,这显然使查找格式说明不匹配导致的问题更加困难! (您的编译器特别有用,它为您提供了printf("pid: %d\n", (int)pid); 的明显类型(即printf("pid: %lu\n", (unsigned long int)pid); 和实际的基础类型pid。)