gpt4 book ai didi

c++ - 将文件中的数据读入单独的 Int 值

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:41:41 28 4
gpt4 key购买 nike

我希望从文件中获取数据值并将它们存储在单独的整数变量中。我有以下变量:

int r;
int c;
int startR;
int startC;

该文件以以下形式提供值:

2 32 12 4

这些只是示例,我需要将这四个值存储在变量中。我正在使用 getline 函数获取行,然后调用 split 函数获取字符串并将其拆分并将其放入四个值中。

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;
}

关于c++ - 将文件中的数据读入单独的 Int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741039/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com