文件I / O无法读取任何内容

时间:2013-11-20 22:13:49

标签: c++ file-io

我在阅读和写出文本文件的内容时遇到了问题。 我试图分别阅读问题,答案和错误的答案,但我没有阅读任何内容。

这是我的代码:

#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;
}

这应该是由行读入并将值赋给变量而垃圾桶就在左边。

问题\ Questions.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";

1 个答案:

答案 0 :(得分:1)

更改此行代码

ifstream myfile(p_filename);

到这个

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

看看会发生什么。

您的代码失败的原因几乎肯定是您无法打开文件,因此首先要测试该理论。