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

时间:2014-11-19 19:41:20

标签: c++ input

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

process_id run_time

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

4 个答案:

答案 0 :(得分:1)

  1. 使用C ++,而不是C
  2. 不要使用std :: cin.getline,使用std :: getline(它适用于std :: string并且更安全)
  3. 使用矢量代替硬尺寸数组
  4. 使用struct的向量而不是“对应的数组”
  5. 不要使用while (!stream.eof())
  6. 以下是可能有用的示例:

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

答案 1 :(得分:-1)

使用ignore [http://www.cplusplus.com/reference/istream/istream/ignore/]

中的istream函数
while (!ManageFile.eof()) 
{
    std::string process_id;
    int run_time;
    ManageFile >> process_id;
    ManageFile.ignore (256, '\t');
    ManageFile >> run_time;
}

答案 2 :(得分:-1)

您可以尝试这样的事情:

while (!ManageFile.eof())
{
    quantum[0] = 0;
    ManageFile>>quantum;
    if (strcmp(quantum, "0") == 0 || atoi(quantum) != 0)
        cout << quantum << endl;
}

当然,你需要包含在头脑中

答案 3 :(得分:-1)

使用fscanf代替ifstream可以让工作变得更轻松。

char str[100];
int n;
....
fscanf(FILE * stream,"%s %d", str, &n);

您将获得str中的字符串和n中的整数。

相关问题