那岩年龄:在C++里,假如来源文件只让读一遍,语句该怎么写?

来源:百度文库 编辑:高校问答 时间:2024/04/28 16:28:21
教授给了一个题目:
从daten.txt文件里读出内容,内容有三列组成
姓 名 银行存款
最后以#结尾。
输入一个叫limit的数,double类型,当银行存款大于那个limit的值时候,把姓,名,银行存款写入hoko.txt的文件

要求limit值需要自己输入,并且daten.txt只允许读一次

-----------------------例如--------------------
limit=10000

daten.txt
Lehmann Horst 12333
Schuster Susi 697
Schlolz Ute 22987
Amthor Fritz 3333
Helbig Walter 11234
#
-----
hoko.txt:
Lehmann Horst 12333
Schlolz Ute 22987
Helbig Walter 11234

我做了一下题目,但是只运行出来一半,不能实现只读一次,而且,不知道到最后#该如何判断:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void main()
{
ifstream datin("E:/c++daten/daten.txt");
ofstream datout("E:/c++daten/hoko.txt");
if(!datin ||!datout)
{
cout<<"文件错误!!"<<endl;
return;
}

string name,vorname;
double konto,limit;
datout.setf(ios::fixed);
datout.precision(4);
datout.setf(ios::right);
cout<<"Limit::"<<endl;
cin>>limit;

do
{
datin>>name>>vorname>>konto;
if(konto>limit)
{
datout<<name;
datout.width(12);
datout<<vorname;
datout.width(12);
datout<<konto;
datout<<endl;
}
}
while (!datin.eof());

}

#include <stdio.h>
#include <string.h>

const int MAX = 256;

void main(void)
{
char str[MAX];
FILE *fin = NULL, *fout = NULL;

fin = fopen("daten.txt", "rt");
fout = fopen("hoko.txt", "wt");
assert(fin != && fout != NULL);

//trim函数为去掉字符串前后的空格
while(0 != strcmp("#", trim(fgets(str, MAX, fp))))
{
//进行比较和写文件操作,这步就省略了
......
}

fclose(fin);
fclose(fout);
}

好像是可以用char型来判断,用ascii码也可以

你提问之前自己先尝试回答,态度很好。

iostream 库里的 getline() 让我们把资料一行行地写进一个 string 对象里。

对 # 的判断只需写 if(s == "#")。

判断 # 之前的那段代码负责删除可能存在于每一行两端的空白字符。
 
 
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

void main() {

    ifstream fin("daten.txt");
    ofstream fout("hoko.txt");

    double limit;
    cout << "Enter the limit: ";
    cin >> limit;

    string s;
    while(getline(fin, s)) {

        // Strip whitespace off both ends.
        int start = s.find_first_not_of(" \t"),
            end = s.find_last_not_of(" \t");
        s = s.substr(start, end - start + 1);

        if(s == "#") break;

        string bank_balance = s.substr(s.rfind(" "));
        if(atof(bank_balance.c_str()) > limit)
            fout << s + '\n';
    }
}