我有以下文件:
WTPZ24 KNHC 032040
TCMEP4
TROPICAL STORM SIMON FORECAST/ADVISORY NUMBER 9
NWS NATIONAL HURRICANE CENTER MIAMI FL EP192014
2100 UTC FRI OCT 03 2014
THERE ARE NO COASTAL WATCHES OR WARNINGS IN EFFECT.
TROPICAL STORM CENTER LOCATED NEAR 18.8N 110.6W AT 03/2100Z
POSITION ACCURATE WITHIN 20 NM
REPEAT...CENTER LOCATED NEAR 18.8N 110.6W AT 03/2100Z
AT 03/1800Z CENTER WAS LOCATED NEAR 18.6N 110.1W
FORECAST VALID 04/0600Z 19.2N 112.2W
MAX WIND 65 KT...GUSTS 80 KT.
64 KT... 10NE 0SE 0SW 10NW.
50 KT... 30NE 30SE 20SW 20NW.
34 KT... 50NE 50SE 40SW 40NW.
FORECAST VALID 04/1800Z 20.0N 114.3W
MAX WIND 75 KT...GUSTS 90 KT.
64 KT... 20NE 10SE 10SW 20NW.
我试图在C中创建一个程序来读取文件并找到单词字符串FORECASt VALID。每次一行都有单词FORECAST VALID我希望程序打印该行并“===>”在线之前。对于文档的其余部分,我只想简单地打印该行。
程序的最终输出应如下所示:
REPEAT...CENTER LOCATED NEAR 18.8N 110.6W AT 03/2100Z
AT 03/1800Z CENTER WAS LOCATED NEAR 18.6N 110.1W
===>FORECAST VALID 04/0600Z 19.2N 112.2W
MAX WIND 65 KT...GUSTS 80 KT.
64 KT... 10NE 0SE 0SW 10NW.
50 KT... 30NE 30SE 20SW 20NW.
34 KT... 50NE 50SE 40SW 40NW.
===>FORECAST VALID 04/1800Z 20.0N 114.3W
MAX WIND 75 KT...GUSTS 90 KT.
64 KT... 20NE 10SE 10SW 20NW.
我确实有一些代码片段可以在没有===>的情况下逐字打印文档。但我只需要帮助如何从一行中隔离FORECAST VALID以便放置===>在这些方面:
FILE *fr; /* declare the file pointer */
main()
{
int n;
char line[800];
char buf[255];
fr = fopen ("wtnt23.knhc.201410141453", "rt"); /* open the file for reading */
while(fgets(line, 800, fr) != NULL)
{
sscanf (line, "%s", buf);
if (buf="FORECAST")
{
printf("===>%s",line);
}
else
{
printf("%s",line);
}
fclose(fr); /* close the file prior to exiting the routine */
} /*of main*/
答案 0 :(得分:3)
if (buf="FORECAST")
完全错了。它不是比较,你不能用=
...
你只需要这样做:
while(fgets(line, 800, fr) != NULL)
{
if(0 == strncmp(line, "FORECAST VALID", strlen("FORECAST VALID")) )
{
printf("===>%s",line);
}
else
{
printf("%s",line);
}
}
答案 1 :(得分:1)
我会使用std::strings
和iostreams
而不是char数组和FILE*
。
有点像:
int main()
{
std::ifstream ifs("wtnt23.knhc.201410141453");
std::string line;
while(std::getline(ifs, line)) // loop as long as getline() succeeds
{
if(line.find("FORECAST VALID") == 0) // line starts with this?
{
// output ===>
}
// output line + linefeed
}
}