【问题标题】:c++ ostream output with setwc ++ ostream输出与setw
【发布时间】:2019-04-20 14:02:16
【问题描述】:

我有一个输出文件名 out

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

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

【问题讨论】:

  • 注意我使用循环来通过两个列表来获取姓名和年龄
  • 我不清楚你真正想要做什么。请展示您的代码并描述它应该做什么以及在哪里做不到。
  • 可以在文档中找到示例。 std::setw 应该有帮助。
  • + 连接是错误的方法。您应该将输出与运算符 &lt;&lt; 连接起来。

标签: c++ string iomanip


【解决方案1】:

你可以试试这样的:

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

【讨论】:

    【解决方案2】:

    就这么简单

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

    setw 不返回可以连接的字符串。它返回一个未指定的类型,可以传递给输出流的operator &lt;&lt;

    【讨论】:

    • 要显示示例中的名称,我们可以使用&lt;&lt; std::left
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    相关资源
    最近更新 更多