【问题标题】:C++ file naming using variables使用变量命名 C++ 文件
【发布时间】:2013-12-09 11:18:52
【问题描述】:

基本上,我希望能够使用在程序中定义的两个变量(程序员未知的值)来创建文件名。我可以只使用一个变量(即 (username + ".txt")) 来做到这一点,但由于某种原因使用两个变量会搞砸。

这是我的代码。

void User::setTicket(std::string username, int i)
{
    std::ofstream fout (username + "Ticket" + i + ".txt");

    // Some code

        fout.close();
}

int i 本质上是一个在 main 循环中初始化的计数数字,因此每次循环进行时都会调用 setTicket,并希望调用结果文件

user1Ticket1.txt
user1Ticket2.txt
user1Ticket3.txt
等等

【问题讨论】:

  • 你读过this吗?

标签: c++ file filenames


【解决方案1】:

数值类型不能隐式转换为或直接附加到字符串。

在 C++11 或更高版本中,有一个库函数可以转换它们:

std::ofstream fout (username + "Ticket" + std::to_string(i) + ".txt");

从历史上看,字符串流可以从任意类型构建字符串:

std::ostringstream ss;
ss << username << "Ticket" << i << ".txt";
std::ofstream fout (ss.str().c_str());

【讨论】:

  • 太棒了,第二个版本成功了,我认为这意味着 Visual Studio 2010 使用的是旧版本的 C++
【解决方案2】:

您必须使用 std::to_string(i) (c++11) 将整数转换为字符串才能使用字符串的运算符 +

另见:http://en.cppreference.com/w/cpp/string/basic_string/to_string

【讨论】:

    【解决方案3】:

    基本上,有 3 种方法可以做到这一点。

    如果你有一个 c++11 编译器,你可以使用 std::to_string(i),正如@Dlotan 指出的那样:

    std::ofstream fout(username + "Ticket" + std::to_string(i) + ".txt");
    

    如果你想使用 boost:

    std::ofstream fout(username + "Ticket" + boost::lexical_cast<std::string>(i) + ".txt");
    

    如果你没有 c++11 编译器也不想使用 boost:

    stringstream ss;
    ss << i;
    std::ofstream fout(username + "Ticket" + ss.str() + ".txt");
    

    【讨论】:

      猜你喜欢
      • 2016-04-18
      • 2011-10-10
      • 1970-01-01
      • 2019-07-05
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      相关资源
      最近更新 更多