上一篇博客中讲到了fprintf玄学报错,在这里将这个问题的解答记录下来。
每次循环之后清零filename
经过多番摸索,发现如果filename字符数组每次循环之后不清零的话,它就会带有上一次的值,至于为什么我也不知道(定义字符数组变量filename时并没有对它进行初始化,它里面会存入一些随机的值)。因此,将上次的代码改正如下:
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
void int2str(int n, char *str);
int main() {
cout << "Hello, World!" << endl;
for (int j = 0; j < 2; j++)
{
vector<int> num(5);
for(int i = 0; i < num.size(); i++ ) num[i] = j * 2;
char str1[] = "../output/", str2[] = "3D points-", str3[10] , str4[] = ".txt";
char filename[25]; //用来存储RANSAC之前的3D点集的.txt文件,文件名如./output/3D points-1.txt
int2str(j+1, str3);
strcat(filename, str1);
strcat(filename, str2);
strcat(filename, str3);
strcat(filename, str4);
FILE *fp;
fp = fopen(filename, "w");
if (fp == NULL ) cout << "Cann't open the file!" << endl;
for (int i = 0; i < num.size(); i++) fprintf( fp, "%d\n", num[i] );
fclose(fp);
memset(filename, '\0', sizeof(filename));
}
return 0;
}
//将整型数j转换成字符串[注:字符串就是字符数组]
void int2str(int n, char *str){
char buf[10] = "";
int i = 0;
int len = 0;
int temp = n < 0 ? -n : n; //temp为n的绝对值
if (str == NULL){
return;
}
while(temp){
buf[i++] = (temp % 10) + '0'; //把temp的每一位上的数存入buf
temp = temp /10;
}
len = n < 0 ? ++i : i; //如果n是负数,则需要多一位来存储负号
str[i] = 0; //末尾是结束符0
while(1){
i--;
if (buf[len-i-1] == 0) break;
str[i] = buf[len-i-1]; //把buf数组里的字符拷到字符串
}
if (i == 0) str[i] = '-'; //如果是负数,添加一个负号
}
上述代码较之前的也就是在fclose(fp);
之后加入了语句memset(filename, '\0', sizeof(filename))
,这条语句起的作用是清零字符数组filename。
利用sprintf代替函数int2str
为了将整型数j转换成字符串我写了一个函数int2str,然而经过师兄的提醒,用c++自带的函数sprintf就能实现这个功能,因此,代码改为如下:
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
for(int j = 0; j < 10; j++){
vector<int> num(5);
for (int i = 0; i < num.size(); i++){
num[i] = j * 2;
}
char str1[] = "../output/3D points-", str2[10], str3[] = ".txt";
char filename[25];
sprintf(str2, "%06d", j+1);
cout << str2 << endl;
strcat(filename, str1);
strcat(filename, str2);
strcat(filename, str3);
cout << filename << endl;
FILE *fp;
fp = fopen(filename, "w");
if(fp == NULL){
cout << "Cannot open the file!" << endl;
return 0;
}
for(int i = 0; i < num.size(); i++){
fprintf(fp, "%d\n", num[i]);
}
fclose(fp);
memset(filename, '\0', sizeof(filename));
}
return 0;
}
显然美观多了!!!
输出结果如下: