我希望从文件中获取数据值,并将它们存储在单独的整型变量中。我有以下变量:
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
}发布于 2018-02-12 17:01:11
直接从文件中读取到您的变量。
#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;
}发布于 2018-02-12 17:28:19
如果解析文件中的信息仍然有问题,可以采用一种非常简单的方法--从getline开始,然后从line创建一个stringstream对象,该对象允许您使用操作符进行连续调用,以从行中获取每个下一个值。例如:
#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 failed\n";
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仔细检查一下,如果你还有其他问题,请告诉我。
发布于 2018-02-12 16:43:04
你可以试试这样的东西。
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“将从文件而不是从标准输入读取数据值。
https://stackoverflow.com/questions/48741039
复制相似问题