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

时间:2018-02-12 07:00:25

标签: c++ file

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

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
}

4 个答案:

答案 0 :(得分:1)

直接从文件中读取变量。

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

答案 1 :(得分:1)

如果您仍然无法解析文件中的信息,可以采取一种非常简单的方法 - 继续getline开始,然后从stringstream创建line对象这将允许您使用操作员进行顺序调用以从您的行获取每个下一个值。例如:

#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

仔细看看,如果您有其他问题,请告诉我。

答案 2 :(得分:0)

你可以尝试这样的事情。

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”将从文件而不是标准输入读取数据值。

答案 3 :(得分:-2)

您只需要将值存储到适当的变量中。

请参阅this for more information.

相关问题