How do I use% d or% c ... in the cout statement?

-1

I am studying C and C ++ and would like to understand how I could transform this code written with printf() into cout , or how to use the %d %x %c , etc. functions. no cout .

int main()
{ 
printf("i make %d program \n" , 2)
system("PAUSE");
return 0;
}
    
asked by anonymous 02.08.2018 / 18:09

2 answers

-1
  • Well, first, you need to know that C ++, it is different, it is not defined by output modellers like% d,% x, or things like that. Instead, you use only the variable and the modeling commands.

Example

int n = 5;    cout < n;

You have printed the value 5 ...

To print in hexadecimal, cout < hex < < n;

And so on, there are several modellers for C ++, you can learn them, on youtube, by searching c ++ workbook, pdf's, basic courses ..

    
02.08.2018 / 18:18
6

You should study stream io and your manipulators . Example:

#include <iostream>
using namespace std;

int main() {
    auto x = 65;
    cout << "i make " << x << " program\n";
    cout << "i make " << hex << x << " program " << endl;
    cout << "i make " << (char)x << " program " << endl;
}

See running on ideone . And in Coding Ground . Also I placed GitHub for future reference .

printf() works with conventions where it replaces a part of the text with something that comes as a parameter , and what is used there as placeholder determines what to do. C ++ uses data streams that are queuing up and producing a result. So he goes on assembling each element and the first item is who gets everything that comes after. The cout is output to the console .

Obviously knowing the value is best put all together in a string only. It is only legal to use this when you do not know what you will have in the placeholder , so in this case we will understand that this x would be a value that comes externally.

The second example calls a handler before sending it to the output, and the hex changes the output format from hexadecimal to number, as %x would do.

I have also used \n and endl , to append both ends of a line have differences between them (see link above).

The third example had to convert from number to char on the hand. Good C compilers configured properly require the same. Note that the stream does not care what kind comes. If the type has a stream set it will know what to do. All basic language types have, and all types should have some stream operator set up, it's like a ToString() of other languages.

In the posted documentation there are several other very useful modifiers for formatting the data. You can even create your own with a little more knowledge.

    
02.08.2018 / 18:27