如何从文件中获取所有字符

问题描述

我有一个包含20个字符(字符)的输入,并且我正在使用动态2D数组将它们存储在其中。我必须从文件中读取字符。为了测试我是否拥有所有角色,我尝试打印出程序正在读取的内容

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

using namespace std;

int main() {
    char *key;
    key = new char[20];
    string *studentName;
    studentName = new string[4];
    char *testResults[4];
    for(int i = 0; i < 4; i++){
        testResults[i] = new char[21];
    }
    ifstream in;
    in.open("Ch12_Ex2Data.txt");
    for(int i = 0; i < 20; i++){
        in >> key[i];
    }
    for(int i = 0; i < 4; i++){
        in >> studentName[i];
        string ans;
        getline(in,ans);
        in.ignore(0,' ');
        for(int j = 0; j < 21; j++){
            //in >> ans;
            if(ans[j] != ' '){
                testResults[i][j] = ans[j];
            }
            else{
                testResults[i][j] = ' ';
            }
        }
    }
    cout << "Key: ";
    for(int i = 0; i < 21; i++){
        cout << key[i];
    }
    cout << endl;
    for(int i = 0; i < 4; i++){
        cout << studentName[i] << " ";
        for(int j = 0; j < 20; j++){
            cout << testResults[i][j];
        }
        cout << endl;
    }
    in.close();
    /* for(int i = 0; i < 4; i++){
        delete [][] testResults;
    } */
    delete [] key;
    for(int i = 0; i < 4; i++){
        delete [] testResults[i];
    }
    /* delete [] testResults; */
    delete [] studentName;
    return 0;
}

解决方法

为了读取文件,您需要在顶部包括<fstream>,然后使用文件名初始化ifstream对象。最后使用get(charName)获得一个字符:

#include <fstream>
#include <iostream>

int main()
{
    std::ifstream inFile{"myfile.txt"};

    char charName{};

    while (inFile.get(charName))
    {
        // here is where you store each char
        // which will be provisionally stored in charName each iteration
    }

    // here is where you print your char array

    return 0;

}

不幸的是,您没有确切解释如何实现2D数组,但是以上是从文件读取的基本知识。