【问题标题】:Why is my string empty when taking input from file?为什么从文件中获取输入时我的字符串为空?
【发布时间】:2020-09-11 18:06:54
【问题描述】:

我有一个充满数字的巨大文件(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();
        }

    }

【问题讨论】:

  • curr 未初始化。 v 应该是 char 吗?它不应该是一个足以容纳您的数字或至少是一个字符串的数字类型吗?
  • 不是问题的原因,而是在开始之前计算行数似乎不必要且效率低下,并且可能会导致问题,因为您不是逐行阅读而是使用行数作为终止条件跨度>
  • 除了ifs.seekg你可能还需要清除steam状态
  • 也没有理由明确关闭 offile,因为它将在其解构中关闭
  • 如何清除steam状态?

标签: c++ string file fstream getline


【解决方案1】:

你有 2 个未初始化的变量,countcurr,你的编译器应该警告你这些。如果它不能确保您已启用编译器警告。

在初始 while 循环中的最后一个 getline 失败后,流将设置 faileof 标志。由于流未处于good 状态,因此对其进行的所有进一步操作都将失败,因此您的seekg 将被忽略,您的所有读取也将被忽略。在您的seekg 之前修复此呼叫ifs.clear();

由于您似乎不需要任何地方的行数预先计算它是不必要的,因为您没有按行读取文件,如果您的文件在一行中有多个值,则会导致错误的行为。您的代码可以简化为:

#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++;
        }
    }
}

【讨论】:

  • 变量 curr 和 count 在我的代码的第 12 行和第 15 行初始化。
  • 不,它们是声明的,不是初始化的
  • 我的“primes.txt”中的每个数字也都在一个新行中。
猜你喜欢
  • 2016-08-03
  • 1970-01-01
  • 2015-03-02
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
相关资源
最近更新 更多