[英]Reading from input file and storing in array c++
我想從看起來像這樣的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;
}
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";
}
}
從istream
使用功能ignore
[ http://www.cplusplus.com/reference/istream/istream/ignore/]
while (!ManageFile.eof()) { std::string process_id; int run_time; ManageFile >> process_id; ManageFile.ignore (256, '\\t'); ManageFile >> run_time; }
您可以嘗試如下操作:
while (!ManageFile.eof())
{
quantum[0] = 0;
ManageFile>>quantum;
if (strcmp(quantum, "0") == 0 || atoi(quantum) != 0)
cout << quantum << endl;
}
當然,你需要包括在內
使用fscanf
代替ifstream
可以使工作輕松ifstream
。
char str[100];
int n;
....
fscanf(FILE * stream,"%s %d", str, &n);
您將在str
獲得字符串,在n中獲得整數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.