[英]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.