天天看點

printf()和scanf()的*修飾符

 printf()和scanf()都可以使用*修飾符來修改轉換說明的含義。但是,它們的用法不太一樣。首先,我們來看printf()的*修飾符。

如果你不想預先指定字段寬度,希望通過程式來指定,那麼可以用*修飾符代替字段寬度。但還是要用一個參數告訴函數,字段寬度應該是多少。

也就是說,如果轉換說明是%*d,那麼參數清單中應包含*和 d對應的值。這個技巧也可用于浮點值指定精度和字段寬度。

#include <stdio.h>
int main(void)
{
unsigned width, precision;
int number = 256;
double weight = 242.5;
printf("Enter a field width:\n");
scanf("%d", &width);
printf("The number is :%*d:\n", width, number); printf("Now enter a width and a precision:\n"); scanf("%d %d", &width, &precision);
printf("Weight = %*.*f\n", width, precision, weight); printf("Done!\n");
return 0;
}
           

變量width提供字段寬度,number是待列印的數字。因為轉換說明中*在d的前面,是以在printf()的參數清單中,width在number的前面。同樣,width和precision提供列印weight的格式化資訊。下面是一個運作示例:

Enter a field width:
6
The number is :   256:
Now enter a width and a precision:
8
3
Weight =  242.500
Done!
           

這裡,使用者首先輸入6,是以6是程式使用的字段寬度。類似地,接下來使用者輸入8和3,說明字段寬度是8,小數點後面顯示3位數字。一般而言,程式應根據weight的值來決定這些變量的值。

scanf()中*的用法與此不同。把*放在%和轉換字元之間時,會使得scanf()跳過相應的輸出項。

#include <stdio.h>
int main(void)
{
int n;
printf("Please enter three integers:\n"); scanf("%*d %*d %d", &n);
printf("The last integer was %d\n", n); return 0;
}
           

跳過兩個整數,把第3個整數拷貝給n。下面是一個運作示例:

Please enter three integers:
2019 2020 2021
The last integer was 2021
           

在程式需要讀取檔案中特定列的内容時,這項跳過功能很有用。

繼續閱讀