如何将多个值存储到一个数组中以供以后打印

How do I store multiple values into an array to be printed out later?

本文关键字:数组 一个 打印 存储      更新时间:2023-10-16

好的,所以在这里我将插入我正在开发的这个程序的代码,以帮助我完成工作。我不想详细介绍它的使用方式,但最重要的是我正在创建一个程序:从用户那里获取两个值,操作它们,然后将它们存储到数组中。

现在我可以用一个非常简单的线性程序来做到这一点,但是我遇到困难的地方是,当程序启动时,它要求用户输入两个值,然后程序存储它,然后当它

再次循环时,它会要求用户再输入两个值,然后我希望它再次存储, 存储的次数取决于用户需要的数据点数量,然后最后我希望它打印出他们输入的所有操作值,最后我希望它将其导出到 txt 文件,但这会在以后出现。我只想把基本的东西弄下来。谁能帮我解决这个问题?

#include <iostream>
#include <set>
double dCoordinates(double x)
{
    return x / 1000;
}
void Store(int x , int y)
{
    int anCoorValues[] = { x, y };
}
int main()
{
    std::cout << "How many data points do you need to enter?" << std::endl;
    int nAmountOfDataPoints;
    std::cin >> nAmountOfDataPoints;
    for (int nCount = 0; nCount < nAmountOfDataPoints; nCount++)
    {
        std::cout << "Enter E/W Coordinates" << std::endl;
        double dEW;
        std::cin >> dEW;
        std::cout << "Enter N/S Coordinates" << std::endl;
        double dNS;
        std::cin >> dNS;
        Store(dCoordinates(dEW),dCoordinates(dNS));
    }
}

你应该在 main 中声明一个容器,然后在需要时将其作为参数传递给其他函数。然后您可以随时输出容器。在您的情况下,最好使用std::vector<std::pair<double, double>>

例如(顺便说一下,为什么函数存储有 int 类型的参数?

#include <vector>
#includde <utility>
double dCoordinates( double x )
{
    return x / 1000;
}
void Store( std::vector<std::pair<double, double>> &v, double x , double y )
{
    v.push_back( { x, y } );
}
int main()
{
    std::cout << "How many data points do you need to enter?" << std::endl;
    int nAmountOfDataPoints;
    std::cin >> nAmountOfDataPoints;
    std::vector<std::pair<double, double>> v;
    v.reserve( nAmountOfDataPoints ) ;
    //...
    // Here you can output the folled vector
    for ( const std::pair<double, double> &p : v )
    {
        std::cout << "( " << p.first << ", " << p.second << " )" << std::endl;
    } 

查看此代码:

#include <iostream>  // std::cout
#include <vector>    // std::vector
#include <utility>   // std::pair, std::make_pair()
#include <algorithm> // std::for_each()
int main()
{
    std::vector<std::pair<double, double> > entered_values;
    std::cout << "How many data points do you need to enter?" << std::endl;
    int nAmountOfDataPoints;
    std::cin >> nAmountOfDataPoints;
    entered_values.reserve(nAmountOfDataPoints);

    for (int nCount = 0; nCount < nAmountOfDataPoints; ++nCount)
    {
        std::cout << "Enter E/W Coordinates" << std::endl;
        double dEW;
        std::cin >> dEW;
        std::cout << "Enter N/S Coordinates" << std::endl;
        double dNS;
        std::cin >> dNS;
        entered_values.push_back(std::make_pair(dEW, dNS));
    }
    std::for_each(std::begin(entered_values), std::end(entered_values), [] (std::pair<double, double> const &i) {std::cout << i.first << "," << i.second << std::endl;});
}
相关文章: