如何使用 c++ 从文件中读取和存储行的特定部分
How can I read and store specific part of a line from a file using c++?
我正在尝试使用 c++ 制作一个测验游戏,为此我想将我所有的问题 (MCQ( 及其答案逐行存储在文本文件中。
采用以下格式"这是什么?a(x b(y c(z d(p" 'a'
现在我想从文件中读取并将其存储在我的测验游戏中。这是字符串变量中的问题和字符变量中的答案。
然后我想检查用户是否输入了正确的答案。
#include <iostream>
#include <fstream>
using namespace std;
int NoOfQuestions = 2;
int counter = 0;
int main(){
ifstream file("c++.txt");
string question;
char a;
while(counter<NoOfQuestions){
getline(file,question);
cout<<question<<endl;
counter++;
}
}
假设您的文件如下所示。你有两个问题。第一个有3个答案,第二个有两个答案:
Is the Earth flat?
3
Yes
No
Maybe
Is the sky blue?
2
Yes
It's cloudy
我们可以创建一个结构来表示问题:
struct Question {
std::string question;
std::vector<std::string> answers;
};
然后我们可以编写一个函数来使用 >>
运算符读取它:
std::istream& operator>>(std::istream& stream, Question& q) {
// Get the question
std::getline(stream, q.question);
// Get the number of answers
int num_answers;
stream >> num_answers;
// Ignore the rest of the line containing the number of answers
std::string _ignore;
std::getline(stream, _ignore);
// Read the answers
q.answers.resize(num_answers);
for(auto& answer : q.answers) {
std::getline(stream, answer);
}
return stream;
}
用法示例:
int main() {
// First block: write the file and close it
{
std::ofstream file("test.txt");
file << "Is the earth flat?n";
file << "3 n";
file << "Yesn";
file << "Non";
file << "Mabyen";
}
// Second block: open the file, and read it
{
std::ifstream file("test.txt");
Question q;
file >> q;
std::cout << "Question: " << q.question << 'n';
std::cout << "Answers: n";
for(auto& answer : q.answers) {
std::cout << answer << 'n';
}
}
}
相关文章:
- 将字符串存储在c++中的稳定内存中
- std::原子加载和存储都需要吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- C++:将控制台输出存储在宏中更好吗
- 在基于范围的for循环中使用结构化绑定声明
- 使用 LuaBridge 将 LuaJIT 绑定到C++会导致"PANIC: unprotected error"
- 使用QProcess执行命令,并将结果存储在QStringList中
- 是否可以将绑定函数存储在容器中?
- C++ 如何将参数绑定到具有相同返回类型的函数,并将它们全部存储在一个容器中
- 为什么免费存储区中对象的生存期绑定到范围
- C++17:是编译器为(静态存储持续时间)const引用绑定创建的可修改的临时对象(和存储)
- boost::绑定在存储时不保存部分参数
- C++11绑定std::函数与存储元组和解包
- Boost绑定和Boost函数,将带有参数的函数存储在向量中,然后执行它们
- 将带有占位符的绑定结果存储在 std::函数中
- OpenGL:着色器存储缓冲区映射/绑定
- BGL:使用绑定属性来存储另一个顶点的顶点描述符
- 如何在c++中存储纬度的小数部分为4 unsigned char
- 如何从精神语义规则绑定/调用存储在fusion::vector中的boost::函数
- 如何绑定、存储和执行std::函数对象