首页 > 解决方案 > 编写包含变量值的多行字符串

问题描述

我有程序参数,要求我有一个包含在程序过程中输入的变量值的格式化字符串。由于涉及的数据量,每个新数据点的换行符将是理想的。

我正在使用 Visual Studio 的 C++ 编译器,并且已经具有以下标头:

//preprocessors
#include <iostream>
#include "MortCalc.h"
#include <string>
#include <istream>
#include <ctime>
#include <cmath>
#include <iomanip>
#include <vector>
using namespace std;

我试图像这样连接值和字符串片段:

//write info to string
    string mortgageInfo =
        "       Principal Of Loan:      $" + mortData.principal + "\n"
        + "     Interest Rate:          " + mortData.interest + "%\n"
        + "     Monthly Payment:        $" + monthlyPayment + "\n"
        + "     Total Loan Paid:        $" + total + "\n"
        + "     Total Interest Paid:        $" + interestOverLife + "\n"
        + setprecision(0) + fixed + "\n"
        + "     Years:          " + mortData.term + "\n"
        + "     Start Date of Loan:     " + mortData.dayStart + "/"          
        + mortData.monStart + "/" + mortData.yearStart + "\n"
        + "     End Date of Loan:       " + mortData.dayEnd + "/" 
        + mortData.monEnd + "/" + mortData.yearEnd + "\n";

但我不断收到此错误:“表达式必须具有整数或无范围枚举类型”。

我将这种格式基于 cout 语句的工作原理,并将所有 '<<' 替换为 '+' 以进行连接,而不是双胡萝卜所指的“下一个语句”。

我在正确的轨道上吗?遗漏了一些明显的东西?这可以做到吗?

标签: c++stringvisual-c++c++17

解决方案


进行字符串连接时不能使用setPrecisionand修饰符。fixed但是,您可以使用 a 来做到这一点std::stringstream

// In the header
#include <sstream>

// In your function
std::stringstream ss;
ss << "       Principal Of Loan:      $" << mortData.principal << '\n';
ss << "       Interest Rate:          " + mortData.interest + "%\n";
// more lines...
string mortgageInfo = ss.str();

推荐阅读