我创建了一个程序,该程序将逐行读取文本文件,并将每行中的各个单词分开(以空格分隔)。现在我希望能够编辑代码,以便第一行的所有标记都为 1,第二行的所有标记都为 2,如果有人可以帮助我,请在下面是我的代码:
#include <iostream>
using std::cout;
using std::endl;
#include <fstream>
using std::ifstream;
#include <cmath>
#include <string>
const int MAX_CHARS_PER_LINE = 512;
const int MAX_TOKENS_PER_LINE = 20;
const char* const DELIMITER = " ";
using namespace std;
int main()
{
string filename;
// create a file-reading object
/*std::ifstream file1("file1.txt", ios_base::app);
std::ifstream file2("file2.txt");
std::ofstream combinedfile("combinedfile.txt");
combinedfile << file1.rdbuf() << file2.rdbuf();*/
ifstream fin;
//enter in file name combinedfile.txt
cout <<"please enter file name (including .txt)";
cin >> filename ;
fin.open(filename); // open a file
if (!fin.good())
return 1; // exit if file not found
// read each line of the file
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
// array to store memory addresses of the tokens in buf
const char* token[MAX_TOKENS_PER_LINE] = {}; // initialize to 0
// parse the line
token[0] = strtok(buf, DELIMITER); // first token
if (token[0]) // zero if line is blank
{
for (n = 1; n < MAX_TOKENS_PER_LINE; n++)
{
token[n] = strtok(0, DELIMITER); // subsequent tokens
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;
}
system("pause");
return 0;
}
所以输出应该是这样的:
Token[1] = This
Token[1] = course
Token[1] = provides
Token[1] = detailed
Token[1] = coverage
Token[1] = of
Token[1] = the
Token[1] = concepts
Token[1] = and
Token[1] = syntax
Token[2] = Coverage
Token[2] = includes
Token[2] = inheritance,
Token[2] = overloaded
Token[2] = operators,
Token[2] = overloaded
Token[2]= default
Token[2] = operators,