从文件加载变量

Loading Variable from a file

本文关键字:变量 加载 文件      更新时间:2023-10-16
at

4
5
6
7

#include<iostream>
#include<stdio.h>
#include <fstream>
using namespace std;
int main()
{
    int data[4], a, b, c, d, e, f;
    ifstream myfile;
    myfile.open("tera.txt");
    for (int i = 0; i < 4; i++)
    {
        myfile >> data[i];
    }
    myfile.close();
    a = data[0];
    b = data[1];
    c = data[2];
    d = data[3];
    cout << a << "t" << b << "t" << c << "t" << d << "n";
    return 0;
}

它也需要并给出垃圾价值。我应该如何使用忽略函数来忽略值。如果有另一个数组给出了BT,则还有一件事,其中包含这样的值:在Bt如何将BT的所有值存储在数组中?

您只需要跳过第一行即可。您还可以添加可选错误处理,否则阅读可能会失败。

if (!myfile)
{
    cout << "can't openn";
    return 0;
}
string temp;
myfile >> temp;
cout << "first line: " << temp << endl;
for (int i = 0; i < 4; i++)
{
    myfile >> data[i];
    if (myfile.fail())
    {
        cout << "errorn";
        myfile.clear();
        myfile.ignore(1000000, 'n');
    }
}