gpt4 book ai didi

c++ - 从文件中读取并比较/合并数据以创建新文件

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

我真的很想得到一些帮助来解决这个问题。我有两个文件,一个 txt 文件和一个 xls 文件,在 txt 文件中它包含一个学生姓名列表和他们的 ID。在 xls 文件中,它包含字母和分配给它们的一些数字。我需要为每个学生创建一个新的 txt 文件,文件名是他们的 ID。在这个文件中,我需要显示分配给构成学生姓名的字母表的数字。请帮助我,在给定的时间内真的无法解决txt file xls file Alphabet.txt

到目前为止,我使用 C++ 能够做的是从 txt 文件中读取数据,我也将 xls 文件转换为 txt 文件并从中读取数据。我需要将数据存储在数组中还是更容易转换为结果文件

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;


int main()
{
ifstream inputa("Students.txt");
ifstream inputb("Alphabet.txt");
if (!inputb.is_open()) std::cout << "Error: File Not Open" << '\n';


/* ofstream output;
output.open("output.txt");
This was just to see if it was getting anything
*/

string name;
string id;
string alphabet;
string number;


while (inputa >> name >> id || inputb >> alphabet >> number) {
/* here i planned to compare the strings using string::find, but it doesnt work */

}







system("pause");

return 0;

最佳答案

在撰写本文时,您仍然没有给出包含 ID 和学生姓名的文件的示例,所以我可能弄错了顺序,但您应该明白了。

我只会读入字母表文件,存储编码,然后一步写出所有学生文件:

#include <cstdlib>
#include <fstream>

static int encoding_map[256] = {0};

bool load_encoding(const char* file_name)
{
std::ifstream file;
file.open(file_name);
if (!file.is_open()) return false;

char from = 0;
int to = 0;
while (file >> from >> to) encoding_map[(int)from] = to;

return true;
}

bool write_student_files(const char* src_file)
{
std::ifstream file;
file.open(src_file);
if (!file.is_open()) return false;

std::string id;
std::string name;

std::ofstream outfile;
while (file >> id >> name)
{
outfile.open(id + ".txt");
for (char c : name) outfile << encoding_map[(int)c];
outfile << '\n';
outfile.close();
}

return true;
}

int main()
{
load_encoding("encoding.txt");
write_student_files("students.txt");
return EXIT_SUCCESS;
}

这是我的编码文件(字母文件),encoding.txt:

a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
k 11
l 12
m 13
n 14
o 15
p 16
q 17
r 18
s 19
t 20
u 21
v 22
w 23
x 24
y 25
z 26

这是我的学生文件,students.txt:

0 bob
1 susan
2 joe
3 becky

如果我用 g++ -std=c++11 main.cpp 编译代码并运行它,我会在同一目录中得到 4 个新文件:

0.txt
1.txt
2.txt
3.txt

例如0.txt的内容是:

2152

如果你愿意,你可以弄乱空格,但是,使用我的简单编码:

b => 2
o => 15
b => 2

意味着输出是正确的(虽然不是很漂亮)。

显然,这并没有做太多的错误处理,也没有处理包含多个单词的名称等,但是您应该能够从这里弄明白。

关于c++ - 从文件中读取并比较/合并数据以创建新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44512846/

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