c++ ostream output with setw

514 Views Asked by At

I have an output file name out

using the below code to add a string to the text file:

string foo = "Hello, foo";
out << foo;

How can I customize a string to input into out file

adding string and numbers with a specific width using setw(7)

Your name is:AName  you are 18  
Your name is:foo    you are 30    

with variable name holding the name and variable age holding the age

how can I make this code works

  out<<  ("Your name is :"+ setw(7)+  name +" you are "  + age);
2

There are 2 best solutions below

1
On

It is just as simple as

std::out << "Your name is :" << std::setw(7) << std::left << name << " you are " << age;

setw does not return a string that you can concatenate. It returns an unspecified type that can be passed to operator << of an output stream.

0
On

You could try something like this:

std::string name = "AName";
unsigned int age = 18;
out << "Your name is:" << setw(7) << name << "you are " << age << "\n";

If you have a struct and database, this might be:

struct Name_Age
{
    std::string name;
    unsigned int age;
};

int main()
{
    std::vector<Name_Age> database;
    Name_Age record;
    record.name = "AName"; record.age = 18;
    database.push_back(record);
    record.name = "foo"; record.age = 30;
    database.push_back(record);

    for (size_t index = 0; index < database.size(); ++index)
    {
        cout << "Your name is:" << setw(7) << database[index].name
             << "you are " << database[index].age << "\n";
    }
    return 0;
}