将文本文件的最后一个数字分配给变量C ++

时间:2013-02-06 14:52:26

标签: c++ variables fstream

我正在做一个用fstream输出素数列表的程序。

到目前为止,我有这个:

int export_list (int lim = 50)
{
    int x;
    last_in_txt = ????????????; // assigns last number on txt

    ofstream file ("Primes.txt" , ios::app);

    if (file.is_open()) // if it opens correctly
    {
        for (x = last_in_txt ; x < lim ; x++)
        {
            if (check_prime (x)) // returns 1 when x is prime, returns 0 when not
            {
                file<< x << " ";
            }
        }
        cout << "Done!" << endl << pressenter;
        cin.get();
    }
    else
    {
        cout << "Unable to open file" << endl << pressenter;
        cin.get();
    }
    return(0);
}

所以,正如你所看到的,这应该将一个素数列表附加到Primes.txt,从素数1234547开始。

Primes.txt看起来像这样:

2 3 5 7 11 13 17 19 23 29 31 37 (...) 1234543 1234547 

我的问题是如何将1234547(这是txt的最后一个数字)分配给变量last_in_txt

其他(不那么重要)的问题: 我应该按照我目前的方式保存数字,还是应该将每个数字存储在一个单独的行中?

2 个答案:

答案 0 :(得分:2)

一种简单的方法:继续阅读并分配,直到读完整个文件。

例如,

int last_in_txt = 0;
{
    ifstream infile("Prime.txt");
    int k;
    while(infile >> k) {
        last_in_txt = k;
    }
}
// Now last_in_txt is assigned properly, and Prime.txt is closed

无论Prime.txt中的数字是否用空格字符(' ')或换行符('\n')分隔,这都很有效。

答案 1 :(得分:1)

我的建议是你使用二进制格式写入文本文件(使用wb中的C)。在这种情况下,您将知道最后一个数字占用多少字节,您将能够使用seekgtellg来获取它。如果你使用纯文本格式,你必须从头读取char,这更容易出错,也更慢。

相关问题