Why we cannot use format specifiers in Cpp? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why we cannot use format specifiers in Cpp?

what happens during compilation when the io stream objects like cout and cin are encountered?it does not look for the format specifier while compilation??

10th Jan 2017, 6:39 PM
Sai Krish
Sai Krish - avatar
1 Answer
0
I'm not 100% sure I understand your question, so here is what I "think" you are asking. Please correct me if I am wrong. In answer to your topic title, who says you cannot? if you use printf() or any of those functions, you can use format specifies because printf() refers to the standard output stream (http://www.cplusplus.com/reference/cstdio/stdout/). With respect to cout, it is synchronized to stdout. From cplusplus.com: "Object of class ostream that represents the standard output stream oriented to narrow characters (of type char). It corresponds to the C stream stdout." and can have its format specifiers altered like with printf(). However, you wouldn't use specifiers like "%s" or "%g". You'd call the appropriate member functions inherited from std::ios_base::fmtflags. With respect to compiling (actually at the compilation stage), I don't think it matters or cares. I think format checks are done during pre-processing. Compilation is compilation. Remember, when you're compiling, it's a multi-pass operation. First pass is pre-processing/syntax checking, second pass is compilation and third is linkage. if the compiler is smart, it notices (and may complain about) unorthodox stream manipulation. If it doesn't, all bets are off. What gets written to the IO buffer and displayed on the screen will be whatever the format is. If you changed cout to use an incorrect format, expect garbage (i.e. same is if you did something like this... printf("%g", "stinkybottom\n"); or std::cout << std::precision(6) << "stinkybottom" << std::endl; During the pre-processing stage, the compiler should flag this as a big fat No-No! If it doesn't, well, garbage in-garbage out!
24th Jan 2017, 4:13 AM
M King
M King - avatar