Set Field Width with width(), setw() - C++ File Stream

C++ examples for File Stream:cout

Description

Set Field Width with width(), setw()

Demo Code

#include <iostream>

int main(int argc, const char *argv[]) {
    int widthValue = 4;
    char sentence[10];

    std::cout << "Enter a sentence:" << std::endl;
    std::cin.width(5);  // input only 5 characters from sentence

    // set field width, then display characters based on that width
    while (std::cin >> sentence) {
        std::cout.width(widthValue++);/* w w  w  .  j  a v  a 2 s  .  c o  m*/
        std::cout << sentence << std::endl;
        std::cin.width(5);  // input 5 more characters from sentence
    }

    return 0;
}

Result


Related Tutorials