+ 1
What is setw() function in C++?
I did try looking it up online. I can't find a simple explanation that is in simple English. I'm taking a college C++ class. One of my assignments is to write a program using rand() method to generate random numbers. The sample code my teacher provided looks like this: cout << setw(8) << rand(); I understand what cout<< and rand() means. I'm mainly a Java learner taking C++ for extra units. Also what does the setw() function have to do with printing random numbers?
3 Réponses
+ 11
Try,
http://www.cplusplus.com/reference/iomanip/setw/
It might be a better explanation.
see setfill() also:
http://www.cplusplus.com/reference/iomanip/setfill/
If you use setfill and use it with the example in setw it should display the spaces introduced by setw() and help make its usage clearer.
You can also look into left and right from <ios>
http://www.cplusplus.com/reference/ios/left/
http://www.cplusplus.com/reference/ios/right/
So to answer your question. Your teacher has used setw() for formatting the screen output.
+ 8
setw() is basically used for setting field width! In simple english, it means your output will be printed after some blank fields (or spaces).
cout<<"hello";
//output will be
hello
cout<<setw(10)<<"hello";
//output will be
hello
PS. value inside the setw function will determine the field width (or number of spaces) before the output!
+ 4
Thanks. You guys rule.