c++ - 从输入文件中读取并存储在数组 C++ 中

标签 c++ input

我想从一个看起来像这样的 file.txt 中读取:

process_id 运行时间

T1 23

T2 75

读取每一行并将运行时间的整数(制表符分隔)存储在数组中

我现在的问题是读取文件的内容..以及如何在制表符分隔后获取整数?

谢谢

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main () 
{
int process_id[100];
int run_time[100];  
int arrival_time[100];
char quantum[50];
int switching;

char filename[50];
ifstream ManageFile; //object to open,read,write files
cout<< "Please enter your input file";
cin.getline(filename, 50);
ManageFile.open(filename); //open file using our file object

if(! ManageFile.is_open())
{
    cout<< "File does not exist! Please enter a valid path";
    cin.getline(filename, 50);
    ManageFile.open(filename);
}

while (!ManageFile.eof()) 
{
    ManageFile>>quantum;
    cout << quantum;

}

//ManageFile.close();
return 0;
}

最佳答案

  1. 使用 C++,而不是 C
  2. 不要使用 std::cin.getline,使用 std::getline(它与 std::string 一起工作并且更安全)
  3. 使用 vector 代替硬维度数组
  4. 使用结构 vector 而不是“对应数组”
  5. 不要使用 while (!stream.eof())

下面是一个可能有用的示例:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>

using namespace std;

struct Record {
    int process_id;
    int run_time;
    int arrival_time;
};

int main() {
    std::vector<Record> records;

    int switching;

    std::string filename;
    ifstream infile;

    while (!infile.is_open()) {
        cout << "Please enter your input file: ";
        std::getline(std::cin, filename);
        infile.open(filename); // open file using our file object

        cout << "File cannot be opened.\n";
    }

    std::string quantum;
    std::getline (infile, quantum); // skip header row

    while (std::getline(infile, quantum)) {
        // e.g.
        Record current;
        std::istringstream iss(quantum);
        if (iss >> current.process_id >> current.run_time >> current.arrival_time)
            records.push_back(current);
        else
            std::cout << "Invalid line ignored: '" << quantum << "'\n";
    }
}

关于c++ - 从输入文件中读取并存储在数组 C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27025543/

相关文章:

c++ - 返回引用时的 std::vector::emplace_back 错误 (C++17)

html - 对齐所有类型的 html 输入

javascript - 如何使用 jquery 获取文件输入中删除文件的值?

javascript - 在 AngularJS 中将 base64 转换为图像文件

初始化指向指针的指针时出现 C++ 错误

c++ - 空类继承的 sizeof() 问题

c++ - 条件变量中触发错误信号的频率如何?

c++ - 形状中的 OpenGL 着色

html - 在没有 html 标记的情况下输入后换行

java - 如何通过System.in获取输入?