如何从 FOR 循环创建一个 txt 文件?
How to create a txt file from FOR loop?
我使用迭代方法编写了 C++ 代码。为此,我使用了 FOR 循环。但是,我需要通过迭代将每个结果保存在同一个文本文件(或数据文件)中作为列。我该怎么做?谢谢你的建议。
这是我的代码的简单版本:
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int i;
main()
{
cout<<"Value 1"<<right<<setw(20)<<"Value 2"<<endl;
for(i=0;i<5;i++)
{
cout<< left << setw(20) << i+10
<< setw(20) << i<<endl;
}
getch();
}
对于大多数用途,使用 CSV 文件会更好。这是一个可以满足您需要的代码。
#include <stdio.h>
int main() {
FILE * fpw; // A file pointer/handler that can refer to the file via a cpp variable
fpw = fopen("data.txt", "w"); // Open the file in write("w" mode
if (fpw == NULL) {
printf("Error"); // Detect if there were any errors
return 0;
}
fprintf(fpw, "Value 1,Value 2\n"); // Write the headers
int i = 0;
for (i = 0; i < 5; i++) {
fprintf(fpw, "%d,%d\n", i + 10, i); // Write the values
}
fclose(fpw); //Don't forget to close the handler/pointer
return 0;
}
输出:
将创建一个文件 data.txt
,内容如下:
Value 1,Value 2
10,0
11,1
12,2
13,3
14,4
我使用迭代方法编写了 C++ 代码。为此,我使用了 FOR 循环。但是,我需要通过迭代将每个结果保存在同一个文本文件(或数据文件)中作为列。我该怎么做?谢谢你的建议。
这是我的代码的简单版本:
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int i;
main()
{
cout<<"Value 1"<<right<<setw(20)<<"Value 2"<<endl;
for(i=0;i<5;i++)
{
cout<< left << setw(20) << i+10
<< setw(20) << i<<endl;
}
getch();
}
对于大多数用途,使用 CSV 文件会更好。这是一个可以满足您需要的代码。
#include <stdio.h>
int main() {
FILE * fpw; // A file pointer/handler that can refer to the file via a cpp variable
fpw = fopen("data.txt", "w"); // Open the file in write("w" mode
if (fpw == NULL) {
printf("Error"); // Detect if there were any errors
return 0;
}
fprintf(fpw, "Value 1,Value 2\n"); // Write the headers
int i = 0;
for (i = 0; i < 5; i++) {
fprintf(fpw, "%d,%d\n", i + 10, i); // Write the values
}
fclose(fpw); //Don't forget to close the handler/pointer
return 0;
}
输出:
将创建一个文件 data.txt
,内容如下:
Value 1,Value 2
10,0
11,1
12,2
13,3
14,4