I / O Stream操纵器 - adjustfield internal - C ++ vs C.

时间:2015-05-09 20:09:00

标签: c++ c io printf cout

程序员学生在这里。我的班级任务的一部分遇到了麻烦。我们的任务是将C ++程序转换为C程序 由于使用了“内部”流操纵器,有一行代码我无法转换。它需要在输出中看起来像这样:

+ 6443.- 6443.

但我似乎无法使用C标准而不是C ++来实现这一点

这是我应该转换的C ++代码:

cout << setprecision(4) << setw(13) << internal << showpoint << showpos << fourth << endl;

我试过这个,但+/-仍然在数字旁边。

printf("%+13.0f. \n", fourth);   

如果整个程序更容易理解整个程序......

#include <stdio.h>
#include <stdlib.h>

main()
{
    //bool first;           //Changing data type for standard C Input
    int first;              //This is in place of the bool
    int second;
    //long third;           //Changing data type for standard C input
    int third;              //This is in place of long
    float fourth;
    float fifth;
    //double sixth;         //Changing data type for standard C input
    float sixth;            //This is place of double

    //cout << "Enter bool, int, long, float, float, and double values: ";
    printf("Enter bool, int, long, float, float, and double values: ");
    //cin >> first >> second >> third >> fourth >> fifth >> sixth;
    scanf("%d %d %d %f %f %f", &first, &second, &third, &fourth, &fifth, &sixth);
    //cout << endl;
    printf("\n");

    //1 - 3
    printf("%d", first);

    if(first > 0)
        printf(" true \n");
    else
        printf(" false \n");

    printf("%d %#x %#o \n", second, second, second);
    printf("%16d \n", third);

    //4
    //cout << setprecision(4) << setw(13) << internal << showpoint << showpos << fourth << endl;
    printf("%+13.0f. \n", fourth); //Issues

    //5
    printf("%15.4e\n", fourth);

    //6
    //cout << left << setprecision(7) << fifth << endl;
    printf("%-.7e \n", fifth); //Issues

    //7 - 12
    printf("%17.3f \n", fifth);
    printf("%-d \n", third);
    printf("%16.2f \n", fourth);
    printf("%13.0f \n", sixth);
    printf("%14.8f \n", fourth);
    printf("%16.6g \n", sixth);

    return 0;
}

1 个答案:

答案 0 :(得分:1)

输出&#39; +&#39;或者&#39; - &#39;作为单独的%c参数,

printf( "%c%13d\n",( (forth >=0)? '+' : '-' ), abs(forth) );