C 如何仅输出文件中字符串的最后5个双精度数字(我的代码错误)
如何从字符串(在文件中)输出最后5个双精度数字?我创建了一个数组来存储这些双精度数据,然后将它们作为数组打印。我已经在函数str_过程中编写了它。我想我做错了什么,因为代码不起作用,而且看起来要小得多,不是吗?谢谢你的关注C 如何仅输出文件中字符串的最后5个双精度数字(我的代码错误),c,arrays,string,char,C,Arrays,String,Char,如何从字符串(在文件中)输出最后5个双精度数字?我创建了一个数组来存储这些双精度数据,然后将它们作为数组打印。我已经在函数str_过程中编写了它。我想我做错了什么,因为代码不起作用,而且看起来要小得多,不是吗?谢谢你的关注 #include<stdio.h> #include<string.h> #include<ctype.h> #include<stdlib.h> #include<progbase.h&g
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
#include<progbase.h>
#include<pbconsole.h>
enum { BUFFER_SIZE = 100 };
int file_process(const char * readFileName, const char * writeFileName);
void str_process (const char * str);
int main(void){
file_process("in.txt", "out.txt");
return 0;
}
/* prints last 5 float numbers of string */
void str_process (const char * str){
/*FILE* fout = fopen("out.txt", "w"); */
int count = 0;
char * ptrEnd;
while(str != '\0'){
double d = strtod (str, &ptrEnd); /* counts floats in string */
count++;
}
double array[count];
if(count == 0) {
fputs("No double numbers!", fout);
}
else {
if(count < 5)
{
for(int i = 0; i < count; i++){
fprintf(fout, "%f ", array[i]);
}
}
else {
for(int i = count - 5; i < count; i++){
fprintf(fout, "%f ", array[i]);
}
}
}
}
int file_process(const char * readFileName, const char * writeFileName){
char buffer[BUFFER_SIZE];
FILE* fin = fopen(readFileName, "r");
FILE* fout = fopen(writeFileName, "w");
if (fin == NULL || fout == NULL){
return EXIT_FAILURE;
}
while(!feof(fin)){
fgets(buffer, BUFFER_SIZE, fin);
buffer[strlen(buffer) - 1] = '\0';
str_process(buffer);
fputs("\n", fout);
}
fclose(fin);
fclose(fout);
return EXIT_SUCCESS;
}
#包括
#包括
#包括
#包括
#包括
#包括
枚举{BUFFER_SIZE=100};
int file_进程(const char*readFileName,const char*writeFileName);
void str_进程(const char*str);
内部主(空){
文件处理(“in.txt”、“out.txt”);
返回0;
}
/*打印字符串的最后5个浮点数*/
void str_进程(const char*str){
/*文件*fout=fopen(“out.txt”,“w”)*/
整数计数=0;
char*ptrEnd;
而(str!='\0'){
双d=strtod(str,&ptrEnd);/*计算字符串中的浮点数*/
计数++;
}
双数组[计数];
如果(计数=0){
fputs(“无双数!”,fout);
}
否则{
如果(计数小于5)
{
for(int i=0;i
此代码存在很多问题。编码时需要使用手册页。例如:
fgets(buffer, BUFFER_SIZE, fin);
buffer[strlen(buffer) - 1] = '\0';
:
终止空字节(aq\0aq)存储在缓冲区中最后一个字符之后
在函数中,这不是使用strtod的正确方法,此外,您从未在数组中放入任何内容:
while(str != '\0'){
double d = strtod (str, &ptrEnd); /* counts floats in string */
count++;
}
double array[count]; // nothing is ever stored in here.
v将该循环更改为:
double[500] doubles;
int i;
for (double d = strtod(str, &ptrEnd); str != ptrEnd; f = strtod(str, &ptrEnd))
{
doubles[i] = d; // store doubles to array.
i++;
}
这样,您现在可以在一个阵列中拥有所有双打
最后,您尝试访问
fin
和fout
,即使它们没有在您使用的函数中声明。您需要在函数之外的文件顶部声明它们:
FILE* fin;
FILE* fout;
Stackoverflow只是在您尝试自己解决问题之后才帮助您解决问题。第一个循环是在同一字符串上反复迭代…步骤1:
double d=strtod(str,&ptrEnd)代码>-->double d=strtod(str和ptrEnd);str=ptrEnd代码>建议避免“代码不起作用”。而是张贴输入、观察结果和预期结果。