我想从一个看起来像这样的 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;
}
最佳答案
- 使用 C++,而不是 C
- 不要使用 std::cin.getline,使用 std::getline(它与 std::string 一起工作并且更安全)
- 使用 vector 代替硬维度数组
- 使用结构 vector 而不是“对应数组”
- 不要使用
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/