c++ - 编写包含变量值的多行字符串
问题描述
我有程序参数,要求我有一个包含在程序过程中输入的变量值的格式化字符串。由于涉及的数据量,每个新数据点的换行符将是理想的。
我正在使用 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 语句的工作原理,并将所有 '<<' 替换为 '+' 以进行连接,而不是双胡萝卜所指的“下一个语句”。
我在正确的轨道上吗?遗漏了一些明显的东西?这可以做到吗?
解决方案
进行字符串连接时不能使用setPrecision
and修饰符。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();
推荐阅读
- sql - 如何使用 SQL 在 Informix 中列出特定数据库的模式?
- excel - 有没有更快的方法来计算每小时挑选的 pc
- java - 如何强制图像立即出现
- php - sortKeys() 不对集合的键进行排序
- rx-swift - 从 Observable 获取最后一个值
- angularjs - 在指令中获取表单控件
- c# - 如何将列表中每条记录的 2 个属性从字符串转换为 int(通过从字符串中提取数字)C#
- python - 如何将浮点 numpy 数组保存到存储空间较少的二进制文件中(例如:不是科学计数法)?
- image-processing - 评估高级算法对嵌入式平台的适用性
- python - 以 Python 方式使 geopy.Point 更具可读性