C++读入txt文件
需要用到的库:
#include <iostream>
#include <fstream>
eg1:
如何读取如下txt文件:
#include <algorithm>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;
int main()
{
ifstream in("data.txt"); //数据txt文件与c文件在同一路径下
double value, discount;
double tmp = 0;
while (in >> value >> discount)
{
tmp += value*discount/100;
}
printf("%lf\n",tmp);
return 0;
}
如果是任意路径呢?
#include <algorithm>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;
int main()
{
ifstream infile("C:\\Users\Desktop\\data.txt"); //路径可改
double value, discount;
double tmp = 0;
while (infile >> value >> discount)
{
tmp += value*discount/100;
}
printf("%lf\n",tmp);
return 0;
}