繁体   English   中英

C++ 从文件中写入多个字符串

[英]C++ writing multiple strings from a file

快速提问。 我正在为一个 uni 作业做我的投资组合 C++ 问题。 是标准差。 我的问题是从文件中读取多个字符串,请参阅此处的文本;

设计并编写一个 C++ 程序,从文件scored.dat中读取一组分数,并将它们的均值和标准差输出到cout

我不打算打扰实际的方程式,我几乎已经对那部分进行了排序。 我的查询直接基于将从文件中读取的文本输出为字符串。 例如,如果文档有这三个分数:

10
15
11

它不是按原样输出文本,而是将它们放入三个字符串中;

Score_One(即 10)
Score_Two(即 15)
Score_Three(即 11)

我希望我在这里说得对,伙计们。 谢谢。

这是一个写起来很有趣的解决方案,我不希望出现这种解决方案。 它也可能具有一些娱乐和/或教育价值。 基本思想是将 a 写为

    std::cout << 10 << 15 << 11 << reset << '\n';
    std::cout << 1 << 2 << 3 << reset << '\n';

为了实现这一点,需要一些机器,但它并没有那么糟糕,真的。 代码是打击:

#include <locale>
#include <iostream>
#include <algorithm>

static int index(std::ios_base::xalloc());
static std::string const names[] = { "One", "Two", "Three", "Four", "Five" };
static std::string const score("Score_");
static std::string const other(" (Which would be ");
std::ostream& reset(std::ostream& out)
{
    out.iword(index) = 0;
    return out;
}

struct num_put
    : std::num_put<char>
{
    iter_type do_put(iter_type to, std::ios_base& fmt, char_type fill,
                     long v) const {
        to = std::copy(score.begin(), score.end(), to);
        if (fmt.iword(index) < 5) {
            to = std::copy(names[fmt.iword(index)].begin(),
                           names[fmt.iword(index)].end(), to);
            ++fmt.iword(index);
        }
        else {
            throw std::runtime_error("index out of range!");
        }
        to = std::copy(other.begin(), other.end(), to);
        to = this->std::num_put<char>::do_put(to, fmt, fill, v);
        *to++ = ')';
        *to++ = ' ';
        return to;
    }
};

int main()
{
    std::cout.imbue(std::locale(std::locale(), new num_put));
    std::cout << 10 << 15 << 11 << reset << '\n';
    std::cout << 1 << 2 << 3 << reset << '\n';
}

你需要做这样的事情:

int raw_score_one = 11; //you have already set this but for the sake of clarity
std::stringstream output;
output << raw_score_one;
std::string Score_One = output.str(); 

对于每个分数...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM