为什么我的字符串从文件中输入时是空的?

问题描述 投票:0回答:1

我有一个巨大的文件,里面全是数字(20亿)。所以这是一个文件分割器,将我的文件分割成100000个数字的组,但这是返回充满空格和输入的空文件。我甚至尝试改变变量的数据类型。我被击中了。

    #include <iostream>
    #include <vector>
    #include <string>
    #include <iterator>
    #include <fstream>
    #include <algorithm>
    using namespace std;
    int main()
    {
        std::ifstream ifs("prime.txt");

        unsigned long long int curr;
        unsigned long long int x = 0;
        string li;
        int count;
        while (getline(ifs, li))
        {
            count ++;
        }
        ifs.seekg(ios::beg);
        string v;
        while (curr < count)
        {
            x++;
            std::string file = to_string(x) ;
            std::string filename = "splitted\\"+file+ ".txt";
            std::ofstream ofile (filename.c_str());

            while (curr < 100000*x )
            {

                ifs >> v ;
                ofile << v << "\n";
                curr++;
            }
            ofile.close();
        }

    }
c++ string file fstream getline
1个回答
0
投票

你有2个未初始化的变量。countcurr你的编译器应该已经警告过你这些问题,如果没有,请确认你已经启用了编译器警告。如果没有,请确认你已经启用了编译器警告。

在最后一个 getline 在你的初始 while 循环失败时,流将会有 faileof 标志设置。由于流不在 good 状态下对它的所有进一步操作都将失败,所以你的 seekg 将被忽略,因为你的所有读数都将被忽略。要解决这个问题,可以调用 ifs.clear(); 在你 seekg.

由于你似乎不需要在任何地方预先计算行数,而且由于你不以行为单位读取文件,如果你的文件在一行上有超过一个值,就会导致不正确的行为。你的代码可以简化为

#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <fstream>
#include <algorithm>
using namespace std;
int main()
{
    std::ifstream ifs("prime.txt");
    if (!ifs)
    {
        std::cout << "error opening input file\n";
        return 1;
    }

    int64_t fileNumber = 0;
    int64_t fileCount = 0;
    std::ofstream ofile;
    while (ifs)
    {
        if (!ofile.is_open() || (fileCount >= 100000))
        {
            ofile.close();
            fileCount = 0;
            fileNumber++;
            std::string file = to_string(fileNumber);
            std::string filename = "splitted\\" + file + ".txt";
            ofile.open(filename.c_str());
            if (!ofile)
            {
                std::cout << "error opening output file\n";
                return 1;
            }
        }
        std::string value;
        if (ifs >> value) {
            ofile << value << "\n";
            fileCount++;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.