テキストファイルを処理すると思われるコードで istream の eof を使用しないようにしています。理由の詳細については、こちらを参照してください。
次のコードは行ごとに読み取ろうとしていますが、各ステップでコードは 1 行ではなく 2 行を読み取っています。
どうやら getline 関数は 2 回実行され、データはstrtok_s
関数によって処理される前に最初に buf に読み込まれます。
内部の getline 命令を無視する場合、処理するデータを書き込むにはどうすればbuf[]
よいですか?
while (getline(fin, line))
//while(!fin.eof())
{
// read an entire line into memory
char buf[MAX_CHARS_PER_LINE];
fin.getline(buf, MAX_CHARS_PER_LINE);
// parse the line into blank-delimited tokens
int n = 0; // a for-loop index
int s = 0;
// array to store memory addresses of the tokens in buf
const char* token[MAX_TOKENS_PER_LINE] = {}; // initialize to 0
char *next_token;
// parse the line
token[0] = strtok_s(buf, DELIMITER, &next_token); // first token
if (token[0]) // zero if line is blank
{
for (n = 1; n < MAX_TOKENS_PER_LINE; n++)
{
token[n] = strtok_s(0, DELIMITER, &next_token);
if (!token[n]) break; // no more tokens
}
}
// process (print) the tokens
for (int i = 0; i < n; i++) // n = #of tokens
cout << "Token[" << i << "] = " << token[i] << endl;
cout << endl;
}
fin.clear();
fin.close();