Mdjon26
Mdjon26

Reputation: 2255

Matching C++ code with C code

I'm trying to get a grasp on C code. Here I am trying to replicate this code in C with code in C++. Or more particularly, I am trying to convert this code from printf to cout using iostream and iomanip instead of printf and and cstdio.

//C CODE 
#include <cstdio> 
#include <cstdlib> 
using namespace std; 

int main() { 
 string header_text = "Basic IO"; 

 srand(0); 
 printf("%-10s::\n", header_text.c_str()); 
 for (int i=0; i<4; i++) { 
 int number1 = rand()%1000; 
 float number2 = (float)number1/91.0; 
 printf("<%3d, %7.4f>\n", number1, number2); 
 } 
 printf("\n");
}

And now I want to convert this to C++.

Here is my attempt:

//C++ code
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main() {
    string header_text = "Basic IO";

    srand(0);
    cout << setw(10) << left << header_text << "::\n";

    for (int i=0; i <4; i++) {
        int number1 = rand()%1000;
        float number2 = (float)number1/91.0;
        cout << "<" <<number1 <<setw(3) << ","   <<setw(7) << setprecision(5)  << number2  << ">\n";
    }


}

It looks like it is mostly correct except the 10.0549 becomes 10.055 in the C++ code. Any idea what is wrong with my C++ code? Although, there could be a couple more errors with it as I'm still very new to understanding C.

Upvotes: 3

Views: 261

Answers (1)

mshildt
mshildt

Reputation: 9362

You want to use std::fixed and a setprecision of 4 to replicate printf's %.4f:

cout << ... << fixed << setprecision(4)  << number2  << ">\n";

Output:

Basic IO  ::
<383,  4.2088 >
<886,  9.7363 >
<777,  8.5385 >
<915,  10.0549>

See here for more info on std::setprecision and std::fixed.

Upvotes: 3

Related Questions