在循环C++中读取文件

Read File in Loop C++

本文关键字:读取 文件 C++ 循环      更新时间:2023-10-16

我有一个函数:

void ReadInput(const char * name)
{
    ifstream file(name);
    cout << "read file " << name << endl;
    size_t A0, A1, A2;
    file >> A0 >> A1 >> A2;
}

现在我想在循环中读取两个文件:INPUT1.txt和INPUT2.txt,例如:

int main ()
{
    for (int i = 1; i < 3; i++){
        ReadInput(INPUT$i);
    }
    return 0;    
}

问题是如何正确定义循环。

感谢您提前抽出时间。

这是整个代码:

#include <iostream>
#include <string>

using namespace std;

void ReadInput(const string& _name){
    ifstream file(_name);
    size_t A0, A1, A2;
    file >> A0 >> A1 >> A2;
}

int main ()
{

    for (int i = 1; i < 3; ++i) {
        string file_name = "INPUT" + to_string(i) + ".txt";
        ReadInput(file_name);
    }
    return 0;
}

好吧,一切都很好,现在我可以在c++98中通过将字符串转换为const-char和字符串流而不是to_string进行编译了。我的目标是运行一个自动化程序,输入文件都在同一个目录中。关于问题可能重复的建议并没有实现这一点,因为我必须在执行时传递输入文件号,据我所知,这对于3000多个文件来说是不切实际的。

更正了下面代码中的一些内容。请记住,要使std::to_string工作,您至少需要使用标志-std=c++11 进行编译

#include <iostream>
#include <string>
#include <fstream> // you need this for std::ifstream
using namespace std;
void ReadInput(const string& _name){
    // ifstream file(name); should be '_name'
    ifstream file(_name);
    // size_t A0, A1, A2 - what if your file contains characters?
    string A0, A1, A2; 
    file >> A0 >> A1 >> A2;
    // output
    cout << "File: " << _name << 'n';
    cout << A0 << " " << A1 << " " << A2 << 'n';
}
int main ()
{
    for (int i = 1; i < 3; ++i) {
        string file_name = "INPUT" + to_string(i) + ".txt";
        ReadInput(file_name);
    }
    return 0;
}

或者,如果文件较长,您可能需要使用std::getline 进行读取

void ReadInput(const string& _name){
    ifstream file(_name);
    string line;
    cout << "File: " << _name << 'n';
    while (getline(file, line)) {
        cout << line << 'n';
    }
}

如果您有许多文件(最多为n_max+1),名称为"INPUTn.txt",其中需要循环,那么以下将是一个潜在的解决方案:

for (int i = 1; i < n_max; ++i) {
    std::string file_name = "INPUT" + std::to_string(i) + ".txt";
    ReadInput(file_name);
}

这需要将ReadInput更改为:

void ReadInput(const std::string& _name);

而不是使用CCD_ 6。

如果您没有C++11访问权限,请使用它来代替std::to_string:

#include <sstream>
//...
template<typename T> std::string to_string(const T& x) {
    return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}

我想你想要的是:

int main (int argc, char* argv[])
{
    using namespace std;
    for (int i = 1; i < argc; ++i) {
        string file_name = string(argv[i]) + to_string(i) + ".txt";
        ReadInput(file_name);
    }
    return 0;
}

有关更多信息,请参阅:https://stackoverflow.com/a/3024202/3537677