[英]Reading integers and strings from a text file and storing in parallel arrays
我有一个存储索引、学生姓名和学生 ID 的文本文件,我正在尝试将它们读入整数数组index
、字符串数组studentName
和studentID
。 我在存储学生姓名时遇到问题,因为它们可能不止一个单词。 我可以用逗号分隔文本文件中的项目并使用getline
但这意味着index
数组必须是字符串类型。 在不更改原始文本文件的情况下是否有解决方法?
原始文件:
1 James Smith E2831
2 Mohammad bin Rahman M3814
3 MJ J4790
const int SIZE = 3;
int index[SIZE];
string studentName[SIZE], studentID[SIZE];
fstream infile("students.txt");
if(infile.is_open()){
int i = 0;
while(i < 3){
infile >> index[i] >> studentName[i] >> studentID[i];
i++;
}
}
更改的文件:
1,James Smith,E2831
2,Mohammad bin Rahman,M3814
3,MJ,J4790
const int SIZE = 3;
string index[SIZE];
string studentName[SIZE], studentID[SIZE];
fstream infile("students.txt");
if(infile.is_open()){
int i = 0;
while(i < 3){
getline(infile, index[i],','); //index array is string
getline(infile, studentName[i],',');
getline(infile, studentID[i],'\n');
i++;
}
}
有很多可能的解决方案,很难说应该使用什么。 取决于您的个人风格以及您对语言的了解程度。
在几乎所有解决方案中,您都会(出于安全原因)使用std::getline
读取完整的行,然后手动拆分该行或使用std::istringstream
进行进一步提取。
最好使用 csv 输入,因为它更清楚什么属于一起。
那么,主要的可能性是什么? 首先是空格分隔的名称
std::regex
然后搜索或匹配例如 "(\d) ([\w ]+) (\w+)"std::vector
中。 std::vector
中的第一个元素是索引,最后一个是 ID,其余的是名称。还有很多
对于 csv,您可以使用
std::sregex_token_iterator
std::vector
并稍后选择所需的值。例子:
std::getline(std::getline(infile >> index >> Comma >> std::ws, name, ','), id);
这取决于你,你想实现什么。
在评论中写下你的偏好,然后我会添加一些代码。
使用给定的输入格式将一行读入一个学生属性是错误的。 您需要阅读一行,然后将这一行中的信息拆分为 3 个属性。
std::stoi
可用于 convert 将读取的行的第一部分转换为int
。 此外,如果您创建一个自定义类型来存储学生的所有 3 个属性,而不是将信息存储在 3 个数组中,那么处理数据会更简单。
请注意,以下代码需要添加逻辑以直接在','
字符之后(甚至可能之前)跳过空格。 目前它只是在名称/ID 中包含空格。 我会把这个任务留给你。
struct Student
{
int m_index;
std::string m_name;
std::string m_id;
};
std::vector<Student> readStudents(std::istream& input)
{
std::vector<Student> result;
std::string line;
while (std::getline(input, line))
{
size_t endIndex = 0;
auto index = std::stoi(line, &endIndex);
if (line[endIndex] != ',')
{
throw std::runtime_error("invalid input formatting");
}
++endIndex;
auto endName = line.find(',', endIndex);
if (endName == std::string::npos)
{
throw std::runtime_error("invalid input formatting");
}
result.push_back(Student{ index, line.substr(endIndex, endName - endIndex), line.substr(endName + 1) });
}
return result;
}
int main() {
std::istringstream ss(
"1,James Smith,E2831\n"
"2, Mohammad bin Rahman, M3814\n"
"3, MJ, J4790\n");
auto students = readStudents(ss);
for (auto& student : students)
{
std::cout << "Index=" << student.m_index << "; Name=" << student.m_name << ";Id=" << student.m_id << '\n';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.