在循环C++中读取文件
Read File in Loop C++
我有一个函数:
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
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中