我在读入和写出文本文件的内容时遇到问题。 我正在尝试分别阅读问题、答案和错误答案,但没有任何内容可读。
这是我的代码:
#include "Question.h"
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
Question::Question()
{
this->m_question = "";
this->m_question = "";
this->m_wrongAns1 = "";
this->m_wrongAns2 = "";
this->m_wrongAns3 = "";
char trash[256];
char value[256];
int count;
}
Question::Question(string p_question, string p_answer, string p_wrongAns1, string p_wrongAns2, string p_wrongAns3)
{
this->m_question = p_question;
this->m_question = p_answer;
this->m_wrongAns1 = p_wrongAns1;
this->m_wrongAns2 = p_wrongAns2;
this->m_wrongAns3 = p_wrongAns3;
char trash[256];
char value[256];
int count;
}
string Question::getQuestion(string p_filename)
{
ifstream myfile(p_filename);
char trash[256];
char value[256];
myfile.getline(trash, 256); //Linebreak
myfile.getline(trash, 256); //Name tag
myfile.getline(value, 256); //Name
m_question.assign(value);
cout << m_question;
return m_question;
}
string Question::getAnswer(string p_filename)
{
return "";
}
vector<string> Question::getWrongAnswers(string p_filename)
{
vector<string> questionList;
vector <string> ::iterator questionIt;
return questionList;
}
这应该是按行读入并将值赋给一个变量,垃圾就剩下了。
问题\问题.txt
Which of the following is NOT a type of virtual collaboration:
Skype
igoogle documents
Hand-written letter Answer
Email
Which of the following are types of CMC?
Video
Instant Messengers Answer
Phone
BlueJ
在 main 中,我只是做了一个简单的调用:
getQuestions("Questions\\Questions.txt";
最佳答案
更改这行代码
ifstream myfile(p_filename);
对此
ifstream myfile(p_filename);
if (!myfile.is_open())
cerr << "could not open file\n";
看看会发生什么。
几乎可以肯定,您的代码失败的原因是您无法打开文件,因此请先测试该理论。
关于c++ - 文件 I/O 未读入任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20108159/