文件I/O没有读取任何内容

File I/O not reading in anything

本文关键字:读取 任何内 文件      更新时间:2023-10-16

我在读取和写入文本文件的内容时遇到问题。我试着分别阅读问题、答案和错误答案,但我没有什么可读的。

这是我的代码:

#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

总的来说,我只做了一个简单的调用:

 getQuestions("Questions\Questions.txt";

更改这行代码

ifstream myfile(p_filename);

到这个

ifstream myfile(p_filename);
if (!myfile.is_open())
    cerr << "could not open filen";

看看会发生什么。

几乎可以肯定的是,你的代码失败的原因是你没有打开文件,所以先测试一下这个理论。