सामग्री पर जाएँ

लेसन 27 · Strings

std::format और std::print से फ़ॉर्मेटिंग

C++ के std::format और std::println की पूरी गाइड: width, fill, alignment, precision, sign, hex व binary, vector और map फ़ॉर्मेटिंग, कस्टम formatter, iomanip।

लगभग हर प्रोग्राम वैल्यू को टेक्स्ट में बदलता है: लॉग की पंक्ति, रसीद, नतीजों की टेबल, या ऐसा फ़ाइल नाम जिसमें संख्या हो। दशकों तक C++ ने इसके लिए दो असंतोषजनक तरीक़े दिए। C का printf छोटा है पर type-safe नहीं, इसलिए गलत %d आपका प्रोग्राम क्रैश कर सकता है। stream (std::cout << ...) type-safe हैं पर लंबी, और उनके फ़ॉर्मेटिंग फ़्लैग चिपके रहते हैं और बाद के आउटपुट में रिस जाते हैं।

C++20 ने std::format (हेडर <format>) जोड़ा, और C++23 ने std::print और std::println (हेडर <print>)। ये दोनों की ख़ूबियाँ जोड़ते हैं: Python की f-string जैसे छोटे {} placeholder, पूरी type safety, और ऐसी format स्ट्रिंग (string) जिनकी जाँच कंपाइल टाइम पर होती है। इस पाठ में पूरी format-spec भाषा (width, fill, alignment, sign, precision, number base), कंटेनर की फ़ॉर्मेटिंग (C++23), अपने टाइप के लिए formatter लिखना, और <iomanip> के समकक्ष शामिल हैं जो आपको stream वाले कोड में अब भी मिलेंगे।

बुनियादी बातें: format, print और println

तीनों फ़ंक्शन (function) एक format स्ट्रिंग और उसके बाद डालने वाली वैल्यू लेते हैं। हर {} एक replacement field है:

  • std::format(fmt, args...) एक std::string लौटाता है।
  • std::print(fmt, args...) standard output पर (या पहले दी गई FILE* या stream पर) लिखता है।
  • std::println(fmt, args...) वही करता है और newline जोड़ता है।
C++ Replacement field

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

आप सारे field को नंबर दे सकते हैं (, ) या किसी को नहीं, पर एक ही format स्ट्रिंग में दोनों शैलियाँ नहीं मिला सकते। दोहरे ब्रेस {{ और }} एक सचमुच का ब्रेस प्रिंट करते हैं।

format स्ट्रिंग की जाँच कंपाइल टाइम पर होती है

format स्ट्रिंग आमतौर पर कंपाइल टाइम constant होनी चाहिए। कंपाइलर उसे पार्स करता है और जाँचता है कि field की संख्या और हर format spec आर्ग्युमेंट (argument) के अनुकूल हैं। गलती कंपाइल एरर होती है, रात 3 बजे का क्रैश नहीं:

C++
std::println("{} and {}", 42);      // एरर: आर्ग्युमेंट कम हैं
std::println("{:d}", "text");       // एरर: स्ट्रिंग के लिए 'd' वैध नहीं
std::string fmt = "{}";
std::println(fmt, 42);              // एरर: fmt constant एक्सप्रेशन नहीं है

जब format स्ट्रिंग सचमुच केवल रनटाइम पर पता हो (जैसे अनुवाद की फ़ाइल से लोड हुई), तो std::vformat(fmt, std::make_format_args(args...)) इस्तेमाल करें। तब एरर रनटाइम पर std::format_error फेंककर बताई जाती हैं। C++26 इसका ज़्यादा आसान नाम std::runtime_format(fmt) जोड़ता है।

format spec की छोटी भाषा

ब्रेस के अंदर, वैकल्पिक आर्ग्युमेंट नंबर के बाद, कोलन format spec शुरू करता है। हर हिस्सा वैकल्पिक है, पर हिस्से इसी क्रम में आने चाहिए:

TEXT
{ arg-id : fill-and-align  sign  #  0  width  .precision  L  type }
हिस्सा उदाहरण मतलब
fill और align <, >, ^, *^ बाएँ, दाएँ, बीच; इससे पहले वैकल्पिक fill कैरेक्टर
sign +, -, स्पेस धनात्मक पर + दिखाएँ, केवल - (डिफ़ॉल्ट), या धनात्मक के लिए स्पेस
# {:#x} alternate रूप: 0x, 0b, 0 prefix; दशमलव बिंदु हमेशा दिखाएँ
0 {:08} संख्या को आगे शून्य से भरें (sign और prefix के बाद)
width {:10}, {:{}} न्यूनतम field चौड़ाई; {} इसे किसी आर्ग्युमेंट से लेता है
precision {:.2f}, {:.3} float के लिए अंक, स्ट्रिंग के लिए अधिकतम कैरेक्टर
L {:L} locale इस्तेमाल करें (अंक समूहन, दशमलव विभाजक)
type d x X o b B c e f g a s ? प्रस्तुति, आर्ग्युमेंट के टाइप पर निर्भर

Width, fill और alignment

width कैरेक्टर की न्यूनतम संख्या तय करती है; लंबी वैल्यू कभी नहीं काटी जातीं। डिफ़ॉल्ट रूप से संख्याएँ दाएँ और टेक्स्ट बाएँ align होता है। चुनने के लिए width से पहले <, > या ^ लगाएँ, और भरने के लिए alignment से पहले कोई भी कैरेक्टर ({ और } को छोड़कर) लगाएँ।

C++ align किए कॉलम वाली रसीद

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

खाली स्ट्रिंग के साथ {:-<36} रेखा खींचने का अच्छा तरीक़ा है: fill कैरेक्टर -, बाएँ align, width 36। आख़िरी पंक्ति dynamic width दिखाती है: spec के अंदर nested {} width अगले आर्ग्युमेंट से लेता है (positional field में आप {0:>{1}} लिखते हैं)। precision भी इसी तरह dynamic हो सकती है: {:.{}f}।

इंटीजर: sign, base और शून्य पैडिंग

इंटीजर के लिए type अक्षर base चुनता है: d दशमलव (डिफ़ॉल्ट), x/X hexadecimal, o octal, b/B binary, और c उस कोड वाला कैरेक्टर। # मेल खाता prefix जोड़ता है, और 0 sign और prefix के बाद शून्य भरता है, जो 0x00ff जैसी चीज़ों के लिए ठीक वही है जो आपको चाहिए।

C++ इंटीजर फ़ॉर्मेटिंग

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

ध्यान दें कि -42 पर {:05} -0042 देता है: sign width में गिना जाता है और शून्य उसके बाद आते हैं।

Floating-point: precision और प्रस्तुति

spec के बिना double वह सबसे छोटा रूप प्रिंट होता है जो वापस पढ़ने पर ठीक वही वैल्यू दे। इसीलिए 0.1 + 0.2 अपनी असली वैल्यू 0.30000000000000004 दिखाता है, उसे छिपाता नहीं। जब आपको तय रूप चाहिए, तो presentation type चुनें:

Type मतलब 1234.5678 के साथ उदाहरण
f तय दशमलव स्थान {:.3f} → 1234.568
e / E scientific {:.3e} → 1.235e+03
g / G सामान्य: fixed या scientific, precision = सार्थक अंक {:.3g} → 1.23e+03
a / A hexadecimal floating point {:a} → 1.34a456d5cfaadp+10
% सपोर्ट नहीं: खुद 100 से गुणा करें
C++ Floating-point फ़ॉर्मेटिंग

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

राउंडिंग सटीक binary वैल्यू पर होती है, इसलिए 2.675 का {:.2f} 2.67 देता है: स्टोर की गई double 2.675 से थोड़ी कम है। पैसों के लिए सटीक दशमलव राउंडिंग चाहिए, तो इसकी जगह पैसे को इंटीजर में रखें (देखें Floating-Point संख्याएँ)।

स्ट्रिंग, कैरेक्टर, बूलियन और पॉइंटर

  • स्ट्रिंग (std::string, std::string_view, const char*) width, fill, alignment और precision लेती हैं, जो काटती है: "truncate" का {:.3} tru प्रिंट करता है।
  • ? (C++23) "debug" रूप प्रिंट करता है: स्ट्रिंग escape के साथ कोट में, कैरेक्टर सिंगल कोट में। tab वाली स्ट्रिंग का {:?} "a\tb" प्रिंट करता है। यूज़र इनपुट लॉग करने के लिए बढ़िया।
  • bool true/false प्रिंट करता है; {:d} 1/0।
  • पॉइंटर: केवल void*, const void* और nullptr फ़ॉर्मेट हो सकते हैं। दूसरे पॉइंटर को static_cast<const void*>(p) से cast करें। वे hex में 0x7ffd5c3a1b2c की तरह प्रिंट होते हैं ({:p} साफ़ type है)।
C++
std::println("[{:>8}] [{:.3}] {:?} {:?}", "right", "truncate", "tab\there", 'x');
// [   right] [tru] "tab\there" 'x'
std::println("{} {:d}", true, true);              // true 1
int value = 5;
std::println("{}", static_cast<const void*>(&value));   // 0x7ffc... जैसा एड्रेस

कंटेनर और रेंज की फ़ॉर्मेटिंग (C++23)

C++23 कंटेनर, रेंज, std::pair और std::tuple को बिना कुछ किए फ़ॉर्मेट करने लायक बनाता है। sequence स्क्वेयर ब्रैकेट में, सेट ब्रेस में, map {key: value} जोड़े के रूप में और pair/tuple कोष्ठक में प्रिंट होते हैं। कंटेनर के अंदर की स्ट्रिंग और कैरेक्टर debug रूप लेते हैं, इसलिए आप ठीक देख सकते हैं कि हर एलिमेंट कहाँ शुरू और ख़त्म होता है।

पहले कोलन के बाद आप रेंज विकल्प जोड़ सकते हैं: n ब्रैकेट हटाता है। दूसरा कोलन हर एलिमेंट पर spec लगाता है।

C++ vector, map और tuple प्रिंट करना

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++23 से पहले आपको हर कंटेनर प्रिंट करने के लिए लूप (loop) लिखना पड़ता था। range formatting को GCC 15, libc++ वाले Clang 17+, या नया MSVC चाहिए। पुराने कंपाइलर पर open-source {fmt} लाइब्रेरी, जिससे std::format निकला, वही सिंटैक्स देती है।

अपने टाइप फ़ॉर्मेट करना

अपने टाइप को std::format और std::println के साथ चलाने के लिए उसके लिए std::formatter specialize करें। सबसे आसान तरीक़ा है मौजूद formatter से inherit करना: तब आपको उसकी पूरी spec भाषा मुफ़्त मिलती है और आप केवल format लिखते हैं।

C++ कस्टम formatter

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

कस्टम spec अक्षरों के लिए अपना parse फ़ंक्शन वाला formatter लिखना भी संभव है; आप उसे stream के operator<< के साथ Operator Overloading में देखेंगे।

स्ट्रिंग कुशलता से बनाना

std::format हर बार नई स्ट्रिंग लौटाता है। जब आप टुकड़ों में टेक्स्ट जोड़ते हैं, तो इसके दो रिश्तेदार अतिरिक्त आवंटन से बचाते हैं:

  • std::format_to(out, fmt, args...) output iterator से लिखता है, जैसे मौजूद स्ट्रिंग में जोड़ने के लिए std::back_inserter(str)।
  • std::formatted_size(fmt, args...) बताता है कि नतीजे में कितने कैरेक्टर होंगे; std::format_to_n तय buffer में अधिकतम n कैरेक्टर लिखता है।
C++
std::string csv;
for (int row = 1; row <= 3; ++row) {
    std::format_to(std::back_inserter(csv), "{},{:.1f}\n", row, row * 1.5);
}
// csv == "1,1.5\n2,3.0\n3,4.5\n"
std::println("{}", std::formatted_size("{}-{}", 10, 200));   // 6

stream वाला तरीक़ा: <iomanip>

C++20 से पहले का कोड, और std::ostream ऑब्जेक्ट (object) में लिखने वाला कोड, <iomanip> के manipulator से फ़ॉर्मेट करता है। आपको इसे आसानी से पढ़ना आना चाहिए, इसलिए यह रहा मिलान:

std::format Stream manipulator चिपकता है?
{:>10} / {:<10} std::setw(10) + std::right / std::left setw एक वैल्यू के बाद रीसेट; left/right बने रहते हैं
{:*>10} std::setfill('*') बना रहता है
{:.2f} std::fixed << std::setprecision(2) बना रहता है
{:x} / {:#x} std::hex / + std::showbase बना रहता है
{:+} std::showpos बना रहता है
bool का {} std::boolalpha (वरना 1/0) बना रहता है

"चिपकता है" वाला कॉलम ही जाल है: ज़्यादातर manipulator stream की state स्थायी रूप से बदलते हैं, इसलिए एक फ़ंक्शन का std::hex बाद में प्रिंट होने वाली हर संख्या को चुपचाप बदल देता है।

C++ iomanip और उसके चिपकने वाले फ़्लैग

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

I/O Stream विस्तार से stream को पूरा समझाता है। नए कोड के लिए std::format और std::println चुनें: फ़ॉर्मेटिंग format स्ट्रिंग में रहती है, एक वैल्यू पर लागू होती है, और रिस नहीं सकती।

printf का क्या? पुराने और C-शैली के कोड में आपको std::printf("%5.2f\n", x) दिखेगा। यह चलता है, और GCC -Wall से इसकी format स्ट्रिंग जाँचता है, पर यह std::string या आपके अपने टाइप प्रिंट नहीं कर सकता, और बेमेल specifier undefined behavior है। std::println("{:5.2f}", x) वही काम सुरक्षित रूप से करता है। C और C++ इनकी तुलना करता है।

अपनी समझ जाँचें

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. std::println("[{:*^7}]", "ab"); क्या प्रिंट करता है?

    ^ वैल्यू को * से भरते हुए width 7 के बीच में रखता है। 5 fill कैरेक्टर में से 2 बाईं ओर और 3 दाईं ओर जाते हैं।
  2. 2. std::format("{:#06x}", 255) क्या लौटाता है?

    0x prefix जोड़ता है, और 0 prefix के बाद कुल width 6 तक शून्य भरता है: 0x00ff।

  3. 3. std::string f = "{}"; std::println(f, 1); कंपाइल क्यों नहीं होता?

    format स्ट्रिंग कंपाइल टाइम पर पार्स और जाँची जाती हैं। रनटाइम std::string की जाँच नहीं हो सकती, इसलिए आपको std::vformat (या C++26 में std::runtime_format) साफ़ तौर पर चुनना होता है।
  4. 4. C++23 में std::println("{}", std::vector<std::string>{"a", "b"}); क्या प्रिंट करता है?

    कंटेनर ब्रैकेट में प्रिंट होते हैं, और उनके अंदर की स्ट्रिंग कोट वाले debug रूप में, ताकि एलिमेंट की सीमाएँ दिखें।
  5. 5. std::cout << std::hex << 255; के बाद आगे std::cout << 16; क्या प्रिंट करेगा?

    std::hex चिपकने वाला है। यह std::dec से वापस बदलने तक असर में रहता है, इसलिए 16, hexadecimal 10 के रूप में प्रिंट होता है।

सारांश

  • std::format स्ट्रिंग लौटाता है; std::print/std::println उसे बाहर लिखते हैं (stdout, stderr या stream पर)। format स्ट्रिंग कंपाइल टाइम पर जाँची जाती हैं।
  • spec का क्रम: {arg:fill align sign # 0 width .precision L type}। width न्यूनतम है; <, >, ^ align करते हैं; कोई भी fill कैरेक्टर चलता है।
  • इंटीजर: x, X, o, b, c; # prefix जोड़ता है; 0 sign और prefix के बाद भरता है।
  • float डिफ़ॉल्ट रूप से सबसे छोटा सटीक रूप प्रिंट करते हैं; तय रूप के लिए .Nf, e, g लें। स्ट्रिंग पर precision काटती है।
  • C++23 कंटेनर, map, pair और tuple फ़ॉर्मेट करता है; n ब्रैकेट हटाता है, {::spec} एलिमेंट फ़ॉर्मेट करता है; ? कोट वाला debug आउटपुट देता है।
  • अपने टाइप फ़ॉर्मेट करने के लिए std::formatter<T> specialize करें (मौजूद वाले से inherit करना सबसे आसान है)।
  • <iomanip> के manipulator stream के लिए यही करते हैं, पर ज़्यादातर चिपकते हैं; नए कोड में std::format चुनें।

अगला पाठ: स्ट्रिंग और संख्याओं के बीच कन्वर्ज़न, जहाँ आप यूज़र के टेक्स्ट को सुरक्षित और तेज़ी से संख्याओं में पार्स करेंगे।

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।