将数据从文件读取到单独的int值

Reading Data from a File into Separate Int Values

本文关键字:单独 int 读取 数据 文件      更新时间:2023-10-16

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

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

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

有关更多信息,请参阅此信息。