在C++中将结果写入多个txt文件
Writing results to multiple txt files in C++
我有以下代码:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream os;
char fileName[] = "0.txt";
for(int i = '1'; i <= '5'; i++)
{
fileName[0] = i;
os.open(fileName);
os << "Hello" << "\n";
os.close();
}
return 0;
}
目的是将我的代码输出写入多个 .txt 文件,最多 64 次。当我把这个循环改成运行超过10个,就是
for(int i = '1'; i <= '10'; i++)
我收到以下错误:
warning: character constant too long for its type
知道如何写入超过 10 个文件吗?此外,如何在每个“你好”之后写一个数字,例如“你好 1 ...你好 10”?
干杯。
我认为您收到该警告的原因是因为您试图将两个字符分配到字符数组的一个槽中:
fileName[0] = i;
因为当i = 10;
时,它不再是一个字符
#include <fstream>
#include <iostream>
#include <string>//I included string so that we can use std::to_string
using namespace std;
int main() {
ofstream os;
string filename;//instead of using a char array, we'll use a string
for (int i = 1; i <= 10; i++)
{
filename = to_string(i) + ".txt";//now, for each i value, we can represent a unique filename
os.open(filename);
os << "Hello" << std::to_string(i) << "\n";//as for writing a number that differs in each file, we can simply convert i to a string
os.close();
}
return 0;
}
希望这能以您满意的方式解决问题;如果您需要进一步说明,请告诉我! (:
我有以下代码:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream os;
char fileName[] = "0.txt";
for(int i = '1'; i <= '5'; i++)
{
fileName[0] = i;
os.open(fileName);
os << "Hello" << "\n";
os.close();
}
return 0;
}
目的是将我的代码输出写入多个 .txt 文件,最多 64 次。当我把这个循环改成运行超过10个,就是
for(int i = '1'; i <= '10'; i++)
我收到以下错误:
warning: character constant too long for its type
知道如何写入超过 10 个文件吗?此外,如何在每个“你好”之后写一个数字,例如“你好 1 ...你好 10”?
干杯。
我认为您收到该警告的原因是因为您试图将两个字符分配到字符数组的一个槽中:
fileName[0] = i;
因为当i = 10;
时,它不再是一个字符
#include <fstream>
#include <iostream>
#include <string>//I included string so that we can use std::to_string
using namespace std;
int main() {
ofstream os;
string filename;//instead of using a char array, we'll use a string
for (int i = 1; i <= 10; i++)
{
filename = to_string(i) + ".txt";//now, for each i value, we can represent a unique filename
os.open(filename);
os << "Hello" << std::to_string(i) << "\n";//as for writing a number that differs in each file, we can simply convert i to a string
os.close();
}
return 0;
}
希望这能以您满意的方式解决问题;如果您需要进一步说明,请告诉我! (: