【问题标题】:Write a Multi-Line String with Variable Values Included编写包含变量值的多行字符串
【发布时间】:2018-11-22 07:03:08
【问题描述】:

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

我正在使用 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 语句的工作原理,并将所有 '

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

【问题讨论】:

  • 您绝对不能将整数添加到字符串...使用std::to_string()...
  • 你应该使用字符串流

标签: c++ string visual-c++ c++17


【解决方案1】:

在进行字符串连接时,您不能使用setPrecisionfixed 修饰符。 但是,您可以使用 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();

【讨论】:

    【解决方案2】:

    你的所作所为与你认为的略有不同...

    这行代码使用了operator+() derivative of the std::string class...不幸的是不允许在其中使用整数或任何其他非字符串值 ...

    你,然而有两种选择:

    1. 使用C++11中的std::to_string()...

    示例:不干净!

    #include <string>
    int main() {
        some_function_that_uses_only_strings("ABC" + std::to_string(number));
    }
    
    1. 或者只使用std::stringstreamstd::cout,它本身就是std::istream,所以它的语法是相同的,而且从语法和您的问题来看都是更好的方法...

    示例:

    #include <sstream>
    int main() {
        std::stringstream some_stream;
        some_stream << first_number << "ABC" << number << std::endl;
        some_function_that_uses_only_strings(some_str.str());
    }
    

    【讨论】:

      【解决方案3】:

      String Literals ("...") 是 const char* 类型,而不是 std::string,并且它们的 operator+ 不是串联而是添加到指向的内存地址。

      要么使用 "..."s 来实际创建 std::string 文字(但 std::fixed 等仍然不起作用)或创建一个

      std::stringstream out; 
      

      然后使用 operator

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多