我知道这个问题之前已被问过一百万次,但大多数问题都比我需要的要复杂得多。我已经知道哪些行会有哪些数据,所以我只想将每一行作为自己的变量加载。
例如,在“settings.txt”中:
800
600
32
然后,在代码中,第1行设置为int winwidth,第2行设置为int winheight,第3行设置为int wincolor。
对不起,我对I / O很新。
答案 0 :(得分:2)
你可以做的最简单的事情就是:
std::ifstream settings("settings.txt");
int winwidth;
int winheight;
int wincolor;
settings >> winwidth;
settings >> winheight;
settings >> wincolor;
但是,这不能确保每个变量都在新行上,并且不包含任何错误处理。
答案 1 :(得分:0)
#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可以与提取运算符一起使用&gt;&gt;就像你使用cin一样。显然,提交I / O要比这更多,但是根据要求,这样做很简单。