c - 如何使用格式说明符从标准输入中读取

标签 c format specifier

我想扫描值并在数字前添加 0,直到它是 4 位数字。

例子:

scanf("%d",&value); //entering '4'..modify the scan somehow with format specifier?  
printf("%d",value); //prints 0004

或另一个例子:

scanf("%d",&value); //entering '12'  
printf("%d",value); //prints 0012

或另一个例子:

scanf("%d",&value); //entering '123'  
printf("%d",value); //prints 0123

对于扫描值已经是 4 位的情况,忽略。

有格式说明符,如 printf("%04d",value),但在扫描语句中指定格式对我来说至关重要。

输入:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

我的输出

            _______1_______
           /                  \
     __2__                __3__
    /        \              /        \
     4         5             6         7
  / \        / \          / \        / \
 8     9    10   11     12    13    14   15

它没有像我希望的那样排列,因为我硬编码了所有数字长度为 4 的情况。

期望的输出:(很好地排列)

                _______0001_______
               /                  \
         __0002__                __0003__
        /        \              /        \
      0004      0005          0006      0007
      / \        / \          / \        / \
   008   009  0010 0011   0012  0013  0014 0015

目前的称呼:

int main()
{
int q[100];
int inputValue;
int qSize=1;

while (inputValue != -1) //scanning until -1 is reached
   {
   cin >> inputValue; //here is each number

//What can I add here to make it 4 digits long? (i.e. adding 0's)

   if (inputValue != -1)
    insertAndSort (q, qSize, inputValue); //sorts a heap
   }

 drawSortedTree (q, qSize);//output
}

最佳答案

这样做:

scanf("%d", &value);    //entering '12'  
printf("%04d", value);  //prints 0012

关于c - 如何使用格式说明符从标准输入中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26598859/

相关文章:

c - 用罗马数字表示年份

string - Powershell字符串到数字功能?

java - 将 float 格式化为最多 N 个小数位

iphone - 是否可以定义适应可变数据的日期格式?

c - printf 打印 %d 说明符的字符而不是数字

c - 使用 malloc 和 calloc 生成矩阵导致混淆行为

c - 为什么自动值可以初始化为陷阱表示而不会导致 UB?

c - 如何正确计算 C 中的单词、换行符和字符

Python:想要使用字符串作为切片说明符