在C++中从文本文件加载变量

Loading Variables from Text File in C++

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

我知道这个问题以前被问过一百万次,但大多数问题都比我需要的更复杂。我已经知道哪些行将有什么数据,所以我只想将每一行加载为自己的变量。

例如,在"settings.txt"中:

800
600
32

然后,在代码中,第1行设置为int winwidth,第2行设置为intwinheight,第3行设置为int wincolor。

对不起,我对I/O很陌生。

可能你能做的最简单的事情是:

std::ifstream settings("settings.txt");
int winwidth;
int winheight;
int wincolor;
settings >> winwidth;
settings >> winheight;
settings >> wincolor;

然而,这并不能确保每个变量都在一个新行上,并且不包含任何错误处理。

#include <iostream>
#include <fstream>
#include <string>
using std::cout;
using std::ifstream;
using std::string;
int main()
{
    int winwidth,winheight,wincolor;       // Declare your variables
    winwidth = winheight = wincolor = 0;   // Set them all to 0
    string path = "filename.txt";          // Storing your filename in a string
    ifstream fin;                          // Declaring an input stream object
    fin.open(path);                        // Open the file
    if(fin.is_open())                      // If it opened successfully
    {
        fin >> winwidth >> winheight >> wincolor;  // Read the values and
                           // store them in these variables
        fin.close();                   // Close the file
    }
    cout << winwidth << 'n';
    cout << winheight << 'n';
    cout << wincolor << 'n';

    return 0;
}

ifstream可以与提取运算符>>一起使用,使用方法与cin非常相似。显然,文件I/O的内容远不止这些,但根据要求,这是为了保持简单。