c++ - 文件 I/O 未读入任何内容

标签 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;
}

这应该是按行读入并将值赋给一个变量,垃圾就剩下了。

问题\问题.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/

相关文章:

c - 如何使用文件操作 malloc 结构数组来执行以下操作?

php - 将字符串数据写入文件(如果已存在则覆盖,如果不存在则创建新的)

c++ - C++函数定义中的 "Class* &cls"是什么意思?

c - 根指针移动到指向二叉搜索树中插入的单词

c - write() 在两种情况下表现不同

java - 无法访问 Java 创建的文件——有时

c++ - 通过引用传递(=返回)函数导出处的 vector

c++ - 在类 B 中创建类 A 所拥有的对象,其中 B 不知道 A

c++:push_back() 和 back() 与指针的行为

c++ - boost::shared_ptr 在多线程中使用它安全吗?