为什么我的字符串打印不正确?

Why are my strings not being printed correctly?

我想编写一段代码,根据一些给定的参数列表为 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

Appearance_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.

这可能是行结尾的问题。如果您在 Windows 中创建文件(因此您有 "\r\n" 行结尾)并在 Linux 中使用此文件,则 getline 的工作方式会有所不同。它将使用 '\n' 作为分隔符,但会将 '\r' 视为单独的字符串。结果,您可能会得到一些等于 "\r" 的出现。在一天结束时,您可以输出:

std::ostringstream s_look;
s_look << "The liquid is; " << "\r" << " with " << p_appearance_2;
std::string look = s_look.str();
std::cout << look << std::endl;
std::cout << std::endl;

这将覆盖字符串的开头,因此您不会在输出中看到 "The liquid is; "