gpt4 book ai didi

c++ - 解析第一行全部为 1's and second line all 2' 的文本文件

转载 作者:行者123 更新时间:2023-11-30 04:15:30 24 4
gpt4 key购买 nike

我已经创建了一个程序,它将一个文件逐行读取一个文本文件,并将每行中的单个单词分开(用空格分隔)。现在我希望能够编辑代码,以便第一行的所有标记都为 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,

最佳答案

如果你只是想把单词分成两个容器,第一个包含第一行的单词,第二个包含第二行的单词,你可以使用 vector 来存储它们,并使用字符串流从一行中提取单词文字:

#include <sstream>
#include <string>
#include<vector>
#include<fstream>
using namespace std;

int main()
{
ifstream infile("test.txt");
string line;
string word;
vector< vector<string> > tokens(2);
for (int ix = 0; ix < 2; ++ix)
{
getline(infile, line);
istringstream iss(line);
while(iss >> word)
tokens[ix].push_back(word);
}
}

此处,tokens[0] 是包含第一行单词的 vector ,tokens[1] 包含第二行单词。

关于c++ - 解析第一行全部为 1's and second line all 2' 的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18271040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com