在C++中从文本文件加载变量
Loading Variables from Text File in C++
我知道这个问题以前被问过一百万次,但大多数问题都比我需要的更复杂。我已经知道哪些行将有什么数据,所以我只想将每一行加载为自己的变量。
例如,在"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的内容远不止这些,但根据要求,这是为了保持简单。
相关文章:
- 将 bmp 文件加载到 TSpeedButton 中
- 如何将文本文件加载到 QListwidget 并将其保存回来
- 从 C 可执行文件加载动态库时收到错误C++"undefined symbol"
- 优化从文件加载QImage
- 将csv文件加载到MySQL C++中
- 从文件加载结构
- 如何在 QT 中显示文件加载状态
- C++ 如何从文件加载异类集合
- 从文本文件加载链表并打印时无限循环
- Kotlin 从文件加载类的集合?
- 如何从文件加载QJsonDocument
- SFML 将图像从 txt 文件加载到矢量中仅加载最后一个图像
- 使用ifstream从DAT文件加载数据
- 从 C 中的文件加载结构时出现分段错误
- 从二进制文件加载列表后,我的代码似乎进入了无限循环
- Qml:从文件加载组件时将参数作为 URL 的一部分传递
- 将浮点数保存在文本文件中,然后从文本文件加载回去(OpenGL和C++)
- 从TXT文件加载迷宫
- 从文件加载uint64_t值
- 如何在 c++ 中将二进制文件加载/读取到"vector<vector< bitset<32> >"中?