将数据从文件读取到单独的int值
Reading Data from a File into Separate Int Values
我希望从文件中获取数据值并将其存储在单独的整数变量中。我有以下变量:
int r;
int c;
int startR;
int startC;
该文件以形式提供值:
2 32 12 4
这些只是示例,我需要将这四个值存储在变量中。我正在使用getline函数获取行,然后调用拆分函数将字符串分开并将其放入四个值中。
getline(fileName, line);
split(line);
void split(string l)
{
//this is where I am struggling to find the best way to get the values stored in the ints
}
直接从文件中读取到变量。
#include <iostream>
#include <fstream>
using namespace std;
int main() {
std::ifstream file("test.txt");
int a, b, c, d;
if (file.is_open()) {
cout << "Failed to open file" << endl;
return 1;
}
if (file >> a >> b >> c >> d) { // Read succesfull
cout << a << " " << b << " " << c << " " << d << endl;
}
return 0;
}
如果您仍然遇到问题,可以从文件中解析信息,则可以采用一种非常简单的方法 - 继续使用getline
开始创建stringstream
的CC_2对象,该对象将允许您允许您使用操作员进行顺序调用以从您的行中获取每个下一个值。例如:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main (void) {
int r, c, startR, startC; /* variable declarations */
std::string fname, str;
std::cout << "Enter a filename: "; /* prompt for filename */
std::cin >> fname;
std::ifstream f (fname); /* open file */
if (!f.is_open()) { /* validate open for reading */
std::cerr << "error: file open failedn";
return 1;
}
std::getline (f, str); /* read line into str */
std::stringstream s (str); /* create stringstream s with str */
s >> r >> c >> startR >> startC; /* parse data */
/* output parsed data for confirmation */
std::cout << "r: " << r << " c: " << c << " startR: " << startR
<< " startC: " << startC << "n";
f.close(); /* close file */
return 0;
}
示例输入文件
$ cat dat/4nums.txt
2 32 12 4
示例使用/输出
$ ./bin/strstreamtst
Enter a filename: dat/4nums.txt
r: 2 c: 32 startR: 12 startC: 4
看事物,让我知道您是否还有其他问题。
您可以尝试这样的东西。
FILE* in = NULL;
int r;
int c;
int startR;
int startC;
errno_t fin = freopen_s(&in, "input.txt", "r", stdin);
assert(0x0 == fin);
cin >> r >> c >> startR >> startC;
在此使用freopen((," CIN"将从文件而不是从标准输入中读取数据值。
您只需要将值存储到适当的变量中。
有关更多信息,请参阅此信息。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 如何在C++中从两个单独的for循环中添加两个数组
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 用C++在单独的头文件中完成函数体
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何将整数值解析为逗号分隔字符串中的单独 int 变量?
- 将一个随机的字符序列和int序列解析为单独的向量
- 将INT和STR输入并将它们存储到两个单独的列表中
- 将数据从文件读取到单独的int值
- 将矢量<矢量>元素的值存储在<int>单独的容器上
- 添加到 int 会更改单独的 char 数组
- 在int main函数中编译并运行的循环在放入单独的函数时不会编译
- 如何在Sandy Bridge上的一系列int中快速计数位到单独的箱子中
- 为什么当我使用一个单独类的int时,它会给我随机数