如何将文本文件读入我的主函数并将其存储在数组中?

时间:2015-04-29 18:07:29

标签: c++

我在我创建的函数中创建了一个文本文件,我正在尝试做的是读取main函数中的文本文件然后将文本文件存储到数组中。在我弄清楚如何做到这两点后,我会将文本文件的答案与正确的答案进行比较。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void Get_Answers();

int main()
{   
    const int NUM_ANSWERS = 20;
    char answers[NUM_ANSWERS] = { 'A', 'D', 'B', 'B', 'C', 'B', 'A', 'B', 'C', 'D', 'A', 'C', 'D', 'B', 'D', 'C', 'C', 'A', 'D', 'B' };
    string textName;

    //Fuction for the users answers
    Get_Answers();

    ifstream textIn;
    textIn.open(textName);

    if (textIn.fail())
    {
        cout << "\nFile not found; program will end";
        return (0);
    }

    cout << endl << endl;
    system("pause");
    return(0);
}

void Get_Answers()
{
    const int NUM_ANSWERS = 20;
    char userAnswers[NUM_ANSWERS];
    string textName;

    cout << "\nEnter a text file name ";
    cin >> textName;
    ofstream textFileOut;
    textFileOut.open(textName);

    for (int i = 0; i < NUM_ANSWERS; i++)
    {
        cout << "\nEnter the test answers ";
        cin >> userAnswers[i];

        textFileOut << userAnswers[i] << '\n';
    }
    textFileOut.close();
}

3 个答案:

答案 0 :(得分:0)

如果你的意思是将每一行存储到数组中,for循环和getline应该可以正常工作。

编辑:根据您之前的回答判断,我会说是的,这是怎么做的。

再详细说明,一个简单的方法是使for循环计算有多少行,然后转到文件的开头并再生成一个for循环:for(int i = 0 ; i!= lines; i ++)

然后在for循环中make it array [i] = getline(file,string);

您可以使用while(!file.EOF())代替for循环和while循环。我只是因为某种原因而更喜欢计算行数。

答案 1 :(得分:0)

您可以按照以下代码执行此操作:

  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    // get length of file:
    is.seekg (0, is.end);
    int length = is.tellg();
    is.seekg (0, is.beg);

    char * buffer = new char [length];

    std::cout << "Reading " << length << " characters... ";
    // read data as a block:
    is.read (buffer,length);

    if (is)
      std::cout << "all characters read successfully.";
    else
      std::cout << "error: only " << is.gcount() << " could be read";
    is.close();

    // ...buffer contains the entire file...

    delete[] buffer;
  }

在此处找到此代码段:http://www.cplusplus.com/reference/istream/istream/read/

替换&#34; test.txt&#34;与您的文件名称。但是,您的主代码无法知道Get_Answers()中创建的文件名是什么。

答案 2 :(得分:0)

好的,根据您的问题和我的调试结果判断,您遇到的问题是您正确读取了函数内部的文件,但是您没有将此数据传递到Get_Answers()函数之外。 / p>

我认为C ++的做法是:

1)在main()函数中初始化一个指向空char数组的指针:

char* userAnswersPointer = new char[NUM_ANSWERS];

2)参数化你的Get_Answer()函数以传递一个指向这个数组的指针:

void Get_Answers(char* userAnswers_Ptr, int N_ANS) {

//...

for (int i = 0; i < N_ANS; i++)
    {
        cout << "\nEnter the test answers ";
        cin >> userAnswers_Ptr[i];

        textFileOut << userAnswers[i] << '\n';
    }

//...

}

3)在main()中正确使用它:

int main() {

    //...

    Get_Answers(userAnswersPointer, NUM_ANSWERS);

    //...

    return 0;
}

我没有编译它,只是写出了我的头,所以随时检查出来。它应该让你知道应该怎么做。