读取值并存储在 c++ 的列表中

发布于 2024-12-01 11:24:26 字数 913 浏览 0 评论 0原文

我有一个包含如下数据的文本文件:

name
weight 
groupcode

name
weight
groupcode

name
weight
groupcode

现在我想将所有人的数据写入输出文件,直到达到最大重量 10000 公斤。

目前我有这个:

 void loadData(){
            ifstream readFile( "inFile.txt" );
            if( !readFile.is_open() )
        {
            cout << "Cannot open file" << endl;
        }
            else
            {
                    cout << "Open file" << endl;
            }

            char row[30]; // max length of a value
            while(readFile.getline (row, 50))
            {
                    cout << row << endl;
                    // how can i store the data into a list and also calculating the total weight?
            }
            readFile.close();
    }

我与 Visual Studio 2010 Professional 合作!

因为我是 C++ 初学者,可能有更好的方法!我愿意接受任何想法和建议,

提前致谢!

i have a text file with data like the following:

name
weight 
groupcode

name
weight
groupcode

name
weight
groupcode

now i want write the data of all persons into a output file till the maximum weight of 10000 kg is reached.

currently i have this:

 void loadData(){
            ifstream readFile( "inFile.txt" );
            if( !readFile.is_open() )
        {
            cout << "Cannot open file" << endl;
        }
            else
            {
                    cout << "Open file" << endl;
            }

            char row[30]; // max length of a value
            while(readFile.getline (row, 50))
            {
                    cout << row << endl;
                    // how can i store the data into a list and also calculating the total weight?
            }
            readFile.close();
    }

i work with visual studio 2010 professional!

because i am a c++ beginner there could be is a better way! i am open for any idea's and suggestions

thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

嘴硬脾气大 2024-12-08 11:24:26
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>

struct entry
{
    entry()
        : weight()
    { }

    std::string name;
    int weight; // kg
    std::string group_code;
};

// content of data.txt
// (without leading space)
//
// John
// 80
// Wrestler
// 
// Joe
// 75
// Cowboy


int main()
{
    std::ifstream stream("data.txt");
    if (stream)
    {
        std::vector<entry> entries;

        const int limit_total_weight = 10000;   // kg
        int total_weight = 0;                   // kg

        entry current;
        while (std::getline(stream, current.name) &&
               stream >> current.weight &&
               stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n') &&  // skip the rest of the line containing the weight
               std::getline(stream, current.group_code))
        {
            entries.push_back(current);

            total_weight += current.weight;
            if (total_weight > limit_total_weight)
            {
                break;
            }

            // ignore empty line
            stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
    else
    {
        std::cerr << "could not open the file" << std::endl;
    }
}

编辑:由于您想要将条目写入文件,因此只需流式传输条目即可,而不是将它们存储在向量中。当然,您可以重载运算符>>和运算符 <<对于条目类型。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>

struct entry
{
    entry()
        : weight()
    { }

    std::string name;
    int weight; // kg
    std::string group_code;
};

// content of data.txt
// (without leading space)
//
// John
// 80
// Wrestler
// 
// Joe
// 75
// Cowboy


int main()
{
    std::ifstream stream("data.txt");
    if (stream)
    {
        std::vector<entry> entries;

        const int limit_total_weight = 10000;   // kg
        int total_weight = 0;                   // kg

        entry current;
        while (std::getline(stream, current.name) &&
               stream >> current.weight &&
               stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n') &&  // skip the rest of the line containing the weight
               std::getline(stream, current.group_code))
        {
            entries.push_back(current);

            total_weight += current.weight;
            if (total_weight > limit_total_weight)
            {
                break;
            }

            // ignore empty line
            stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
    else
    {
        std::cerr << "could not open the file" << std::endl;
    }
}

Edit: Since you wannt to write the entries to a file, just stream out the entries instead of storing them in the vector. And of course you could overload the operator >> and operator << for the entry type.

拥抱我好吗 2024-12-08 11:24:26

嗯,这是一个线索。您是否发现您的代码与问题描述之间不匹配?在问题描述中,数据以行为一组,包括名称、重量、组代码和一个空行。但是在您的代码中,您每次循环时只读取一行行,每次循环时您应该读取行。所以像这样的东西

char name[30];
char weight[30];
char groupcode[30];
char blank[30];
while (readFile.getline (name, 30) && 
    readFile.getline (weight, 30) && 
    readFile.getline (groupcode, 30) && 
    readFile.getline (blank, 30)) 
{
    // now do something with name, weight and groupcode
}

在很长一段时间内并不完美,但希望能让你走上正确的轨道。请记住,代码的结构应与问题描述的结构相匹配。

Well here's a clue. Do you see the mismatch between your code and your problem description? In your problem description you have the data in groups of four lines, name, weight, groupcode, and a blank line. But in your code you only read one line each time round your loop, you should read four lines each time round your loop. So something like this

char name[30];
char weight[30];
char groupcode[30];
char blank[30];
while (readFile.getline (name, 30) && 
    readFile.getline (weight, 30) && 
    readFile.getline (groupcode, 30) && 
    readFile.getline (blank, 30)) 
{
    // now do something with name, weight and groupcode
}

Not perfect by a long way, but hopefully will get you started on the right track. Remember the structure of your code should match the structure of your problem description.

§普罗旺斯的薰衣草 2024-12-08 11:24:26

有两个文件指针,尝试读取输入文件并继续写入o/p 文件。同时有一个计数器并随着重量不断增加。当weight >= 10k时,断开循环。届时您将在 o/p 文件中获得所需的数据。

使用此链接获取 I/O API 列表:
http://msdn.microsoft.com/en-我们/库/aa364232(v=VS.85).aspx

Have two file pointers, try reading input file and keep writing to o/p file. Meanwhile have a counter and keep incrementing with weight. When weight >= 10k, break the loop. By then you will have required data in o/p file.

Use this link for list of I/O APIs:
http://msdn.microsoft.com/en-us/library/aa364232(v=VS.85).aspx

梦亿 2024-12-08 11:24:26

如果您想自己努力构建一个工作程序,请阅读本文。如果您更愿意通过示例学习并研究 C++ 输入/输出的强大示例,我绝对建议您仔细研究 Simon 的代码。

首先要做的事情是:当您编写“char row[30];”时,您创建了一个包含 30 个字符的行缓冲区。
在下一行中,您应该将 readFile.getline(row, 50) 调用更改为 readFile.getline(row, 30)。否则,它将尝试读取 50 个字符,如果某人的名字超过 30 个字符,则缓冲区后面的内存将被损坏。所以,这是一个禁忌。 ;)

如果您想学习 C++,我强烈建议您使用 I/O 标准库,而不是 rplusg 建议的 Microsoft 特定库。 ifstream 和 getline 的使用方向是正确的。如果你想学习纯 C++,Simon 在他的评论中关于将字符数组切换为 std::string 的想法是正确的。

不管怎样,约翰给出了关于围绕问题描述构建程序的很好的建议。正如他所说,您将需要在循环的每次迭代中阅读四行。当您阅读权重线时,您将需要找到一种方法来从中获取数字输出(如果您坚持使用字符数组,请尝试 http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/,或尝试 http://www.cplusplus.com/reference/clibrary/cstdlib/atof/对于非整数)。然后您可以将其添加到跑步总体重中。每次迭代,根据需要将数据输出到文件,一旦你的总重量 >= 10000,你就知道要跳出循环了。

但是,您可能根本不想在 while 条件内使用 getline:由于每次循环迭代必须使用 getline 四次,因此您要么必须使用类似于 Simon 的代码,要么将结果存储在四个单独的缓冲区中,如果您这样做(否则,在读入下一行之前,您将没有时间读取重量并打印出该行!)。

相反,您也可以将循环构造为 while(total <= 10000) 或类似的东西。在这种情况下,您可以在循环内使用四组 if(readFile.getline(row, 30)) ,并且您将能够读取权重并在每组之间打印出内容。在将总权重推至超过 10000 的迭代之后,循环将自动结束……但如果到达文件末尾,您也应该打破它,否则您将永远陷入循环中。 :p

祝你好运!

If you want to struggle through things to build a working program on your own, read this. If you'd rather learn by example and study a strong example of C++ input/output, I'd definitely suggest poring over Simon's code.

First things first: You created a row buffer with 30 characters when you wrote, "char row[30];"
In the next line, you should change the readFile.getline(row, 50) call to readFile.getline(row, 30). Otherwise, it will try to read in 50 characters, and if someone has a name longer than 30, the memory past the buffer will become corrupted. So, that's a no-no. ;)

If you want to learn C++, I would strongly suggest that you use the standard library for I/O rather than the Microsoft-specific libraries that rplusg suggested. You're on the right track with ifstream and getline. If you want to learn pure C++, Simon has the right idea in his comment about switching out the character array for an std::string.

Anyway, john gave good advice about structuring your program around the problem description. As he said, you will want to read four lines with every iteration of the loop. When you read the weight line, you will want to find a way to get numerical output from it (if you're sticking with the character array, try http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/, or try http://www.cplusplus.com/reference/clibrary/cstdlib/atof/ for non-whole numbers). Then you can add that to a running weight total. Each iteration, output data to a file as required, and once your weight total >= 10000, that's when you know to break out of the loop.

However, you might not want to use getline inside of your while condition at all: Since you have to use getline four times each loop iteration, you would either have to use something similar to Simon's code or store your results in four separate buffers if you did it that way (otherwise, you won't have time to read the weight and print out the line before the next line is read in!).

Instead, you can also structure the loop to be while(total <= 10000) or something similar. In that case, you can use four sets of if(readFile.getline(row, 30)) inside of the loop, and you'll be able to read in the weight and print things out in between each set. The loop will end automatically after the iteration that pushes the total weight over 10000...but you should also break out of it if you reach the end of the file, or you'll be stuck in a loop for all eternity. :p

Good luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文