使用setw的c ++ ostream输出

时间:2018-11-17 17:39:25

标签: c++ string iomanip

我的输出文件名为

使用以下代码将字符串添加到文本文件:

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

如何自定义字符串以输入到文件

使用setw(7)添加具有特定宽度的字符串和数字

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

变量name保留名称,变量age保留年龄

如何使此代码有效

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

2 个答案:

答案 0 :(得分:0)

就这么简单

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

setw不会返回您可以连接的字符串。它返回一个未指定的类型,该类型可以传递到输出流的operator <<

答案 1 :(得分:0)

您可以尝试这样的事情:

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

如果您有struct和数据库,则可能是:

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;
}