请问如何一行一行的读取一个文本文件,对每一行进行字符匹配呢?

dc128 2003-10-09 10:52:09
不用MFC我就蒙了……,基础太差了,想读一行到一个字符串里匹配一次,是用fscanf还是什么函数呢~请教各位了
...全文
291 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
dc128 2003-10-10
  • 打赏
  • 举报
回复
我要从文本文件中读取一些数据,所以要读一行,匹配字符串,如果没有没有匹配到,就读取下一行再匹配,我知道用CSTIDOFILE的Readstring函数可以实现,不知道标准C+怎么实现~,请指教一下~,先多谢了
TianGuangZao 2003-10-10
  • 打赏
  • 举报
回复
text.txt
banara
apple
orange
...

or

banara apple orange ...
TianGuangZao 2003-10-10
  • 打赏
  • 举报
回复
标准 C+ 是什么? 抱歉我没学过。不过我会点 C++ 和 ANSI C
这里我偷个懒,从 lippman 的 Essential C++ 里摘了个例子,稍改一下。

// Reading strings from a file
// and comparing with a known string
// until find a matched string
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

#define MAXLINE 100 // max length of each line
int main()
{
char strKey[] = "apple"; // known string
char buf[MAXLINE]; // temp buffer

// infile opened in output mode
ifstream infile("text.txt", ios_base::out);

if (!infile)
{
// open failed for some reason ...
cerr << "Unable to open the file!\n";
}
else
{
// reposition to front of file to begin reading
infile.seekg(0);

int match;
// ok: read each line of the input file
while (infile >> buf)
{
if ( (match = strcmp(strKey, buf)) == 0) // match
{
printf("Find it!\n");
break;
}
}
if (match != 0)
printf("Match nothing!\n");
}
}


TianGuangZao 2003-10-09
  • 打赏
  • 举报
回复
读下一行是什么意思???
能具体讲一下你要实现什么功能吗?
好对症下药。
dc128 2003-10-09
  • 打赏
  • 举报
回复
请问读完一行怎么读下一行呢?
TianGuangZao 2003-10-09
  • 打赏
  • 举报
回复
如果你想从 stdin 读入一行,不妨试试下面:
void myGets(char *str, int num, FILE *stream)
{

/* Don't use gets and scanf, fgets is your best selection.
* Note that fgets() reads the whole input characters, including the '\n'.
* Your best bet is to use fgets to read from stdin, then sscanf to work on
* the string.
*/

char *pnl; /* new line pointer */
char inpBuf[BUFSIZ];

fgets(inpBuf, num, stream);

if ( (pnl = strchr(inpBuf, '\n')) ) /* truncate the newline */
*pnl = '\000';
sscanf( inpBuf, "%s", str);

}

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧