这是我的问题,我必须从文本文件中读取某些数据。怎么样?
例如:“test1.txt”包含一些数据,如
IEEEXtreme 2008版将于2008年3月8日举行
我的“keyword.txt”包含:
2008地方
我必须阅读“2008”字样到“地方”字样的文字。
////////////////////////////////////////////
让我们这么简单...... 你能用这段代码帮我吗?#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="This is a simple string";
char * p1,* p2;
p1 = strstr(str,"is");
p2 = strstr(str,"string");
puts (str);
system("Pause");
return 0;
}
我不想让它只读到字符串。
答案 0 :(得分:0)
阅读fgets
中的行(p
)(strstr
中存储),然后p
中的p1
,以获取“2008”(存储在p2
中)和另一个对于“地点”(存储在p1 + strlen("2008")
),它们之间(从p2
到ler_pc
)就是您所需要的......
看到来源后编辑(代码审核:P不是算法审核)
malloc
中的:
calloc
,calloc
)(完成后不要忘记释放它(在调用方))char str[60] = {0}
分配内存,则无需将终结符置为零字节。或者...... ler_frases
也可能有效,具体取决于您的编译器p1[aux] = '\0'
中的
p2
离开循环,每次都将它设置为零是没有意义的(或者从上面看3号)。 strcmp(palavra, p1)
... palavra
do ... while
未初始化,因此您不知道其中有什么:(可能您需要strcmp(palavra, p1) == 0
循环,而不是一段时间。< / LI>
!strcmp(palavra, p1)
可写为excerto
while ((cntrl = 1)
。因为你没有使用它,所以没有任何意义。==
可能你的意思是sizeof(excerto)
(零部分相同)strlen()
始终是指针的大小,而不是字符串的长度。 main
为您提供字符串的长度。pause
中的
PAUSE
!= Pause
!= system
p1 = strstr(str,"is");
时出现。通常:
第二次来源的第二次修改
对于这个具体案例:
is
将返回一个指向字符串中第一个" is"
的指针...即:第3个字符(“This”包含“is”)...所以你可能想要p2 = strstr(str,"string");
/* allocate enough memory for the string between " is" and "string" */
size_t len = p2 - p1 + strlen(" is") + 1;
char* between = (char*)(calloc(len, sizeof(char));
/* and copy out the string from the original*/
strncpy(between, p1 + strlen(" is"), len);
将为您提供指向字符串的指针。
现在你需要做一些事情:
between
所以现在在{{1}}你有所需的字符串(我希望我能正确理解你想要的东西)。
PS:放回原始代码,其他人可以从中学习。