【发布时间】:2022-01-03 01:09:47
【问题描述】:
我想编写一段代码,从几个给定的参数列表中为 D&D 5e 创建一个随机药水列表。我几乎完成了,除了一行代码之外,每一段代码都能正常工作。
我期待这样的输出:“液体是:黄色,带有颜色斑点。”。 相反,我得到了这个:“有颜色的斑点。”。基本上,整个部分: “液体是:”被省略。奇怪的是,当颜色为“深红色”时,它在一种情况下效果很好。
这是最小的工作示例:
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <fstream>
#include <sstream>
int main(int argc, char** argv)
{
std::vector<std::string> appearance;
std::vector<std::string> appearance_2;
std::ifstream d_appearance("appearance.txt");//20 entries
std::ifstream d_appearance_2("appearance_2.txt");//20 entries
std::string line;
std::string line_2;
for(int i = 0; i < 20; i++)
{
getline(d_appearance, line);
appearance.push_back(line);
getline(d_appearance_2, line_2);
appearance_2.push_back(line_2);
}
std::random_device generator;
std::uniform_int_distribution<int> twenty_dis(0,19);
std::string p_appearance = appearance[twenty_dis(generator)];
std::string p_appearance_2 = appearance_2[twenty_dis(generator)];
for(int i = 0; i < 1; i++)
{
std::ostringstream s_look;
s_look << "The liquid is; " << p_appearance << " with " << p_appearance_2;
std::string look = s_look.str();
std::cout << look << std::endl;
std::cout << std::endl;
}
return 0;
}
我希望我只是将文本文件作为代码块放在这里没问题: 外观
Clear
Blue
Green
Red
Pale Green
Pink
Light Blue
White
Black
Dark Grey
Light grey
Yellow
Orange
Gold
Orange
Bronze
Metallic
Purple
Brown
Dark Red
外观_2
flecks of colour.
swirls of colour.
fizzing bubbles.
bubbles suspended in it.
some kind of bone floating in it.
leaves and flowers in it.
two separated liquid phases.
a bright glow.
a soft glow.
stripes of colour.
translucency.
a cloudy murkiness.
blood within it.
dirt floating in it.
chunks of metal in it.
some type of gore from a slain creature.
steam coming from it.
a face in the liquid.
constantly moving and shifting liquid.
a constant heat.
【问题讨论】:
-
当您使用调试器运行此代码时,您看到了什么?这就是调试器的用途,如果您不知道如何使用它,这是一个学习在调试器中一次运行程序、监控所有变量及其值变化并分析您的程序的好机会程序的逻辑和执行。您应该可以使用您的调试器在这个和您编写的所有未来程序中发现所有简单的问题,全部由您自己完成。
-
我在 vs 中运行相同的代码,每次尝试都可以正常工作。我看不出有什么问题。
-
@Leon-JosipDzojic 您确定这些文件已成功打开吗?显然,您只是假设文件已成功打开,但可能没有。当我使用
cin并更改循环时,我不能duplicate the issue。 -
@Leon-JosipDzojic
if ( !d_appearance || !d_appearance_2) { then one of the files did not open successfully }。如果发生这种情况,请不要执行假定两个文件都有效的代码。可能您只想打印一个错误和return -1;或类似的东西。 -
您的文件中的行尾是什么?你在什么操作系统上运行这个程序?
标签: c++ string printing output cout