标准 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");
}
}
/* 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);