我将尝试按目前的问题和解决方案进行详细描述。我目前拥有的解决方案不是最优的,我想使其更好。
注意:char inputline[1024]
没有特定格式,可以包含任何格式的字符串。char inputline [1024]从具有数千行的文件中逐行读取行。这就是为什么优化对我来说非常重要的原因。
FILE *outfile = fopen("tests.txt", "w");
int start_index = 1; //index from where I want to write the characters from the inputline array to the file
int prev_index = start_index; //keep track of last character position written to file
char inputline[1024] = {"12044 This is the test String 2019 to 2025 is another test& and 2050"};
int loop_count = 6; // This can vary as I have just hardcoded a value here for testing
int i;
for(i=0; i<loop_count; ++i)
{
fprintf(outfile, "%c", inputline[prev_index + i]);
}
prev_index = prev_index + loop_count;// this keeps track of last position of character written to file at end
Sample input in char inputline[1024] = {"This is my day in 2020 1230023"}
Desired output in tests.txt: (for loop will loop 6 times as loop_count is 6)
his is
问题是我正在阅读"%c"
,这不是很理想,我想%s
改用它。但是我无法理解如何在写入文件时通过指定in格式说明符将其转换为fprintf(outfile, "%c", inputline[prev_index + i]);
要使用"%s"
的prev_index + i
格式,因为我只希望inputline[prev_index + i]
基于要写入文件的循环使用来自其中的字符。
您可以使用格式说明符%.*s
并传入length
#include <stdio.h>
int main(void) {
int start_index = 1;
int length = 6;
char inputline[] = "This is my day in 2020 1230023";
printf("%.*s\n", length, inputline + start_index); // you can use fprintf(outfile, "%.*s", length, inputline + start_index); here
return 0;
}
输出:
他的是
另外,您可以使用strncpy()
创建子字符串并使用它:
#include <stdio.h>
#include <string.h>
int main(void) {
int start_index = 1;
int loop_count = 6;
char inputline[] = "This is my day in 2020 1230023";
char substr[1024];
strncpy ( substr, inputline + start_index, loop_count);
substr[loop_count] = '\0';
printf("%s\n", substr); // you can use fprintf(outfile, "%s", substr); here
return 0;
}
请注意,您必须#include <string.h>
在代码中
输出:
他的是
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句