【发布时间】:2015-04-11 05:50:40
【问题描述】:
我正在运行以下程序。我在B.txt 中获取前63 个字符值,然后在A.txt 中附加浮点值,从A.txt 的第62 列开始,在B.txt 行的末尾
所以如果 B.txt 包含:
I am running the following program below. I am taking the firstXXXXXXXX
并且 A.txt 包含:
I am running the following program below. I am taking the fir3.14
我希望 B.txt 看起来像:
I am running the following program below. I am taking the first3.14
但是,我得到的输出是:
I am running the following program below. I am taking the firstBUNCH OF JUNK3.14
int main()
{
loadfileB("B.txt");
return 0;
}
void loadfileB(char* fileName)
{
FILE* fp = fopen(fileName, "r");
char line[82];
vector<int> rownum;
vector<float> temp;
temp = loadfileA("A.txt");
int i = 0;
ofstream fout("output.txt");
while (fgets(line, 81, fp) != 0)
{
radius=temp[i];
char buffer[64];
strncpy(buffer, line, 63);
fout << buffer<< " " << radius << endl;
i++;
}
fclose(fp);
}
vector<float> loadfileA(char* fileName)
{
FILE* fp = fopen(fileName, "r");
char line[82];
vector<int> rownum;
vector <float> tempvec;
int i = 0;
while (fgets(line, 81, fp) != 0)
{
float temp;
getFloat(line, &temp, 60, 6);
tempvec.push_back(temp);
}
fclose(fp);
return tempvec;
}
void getFloat(char* line, float* d, int pos, int len)
{
char buffer[80];
*d = -1;
strncpy(buffer, &line[pos], len);
buffer[len] = '\0';
sscanf(buffer, "%f", d);
}
【问题讨论】:
-
你的第一个问题是你使用 C 函数和 C++ 的东西。
标签: c++ string char scanf strncpy