Reading in characters and creating array c++

2019-03-06 05:00发布

How would one go about reading in a line of characters from a file. First the program reads in an integer from the file. That number indicates how many characters to read in in the next step.Next reads the characters in and store them in an array. So how do i create the 'char' variable so that i can correctly read in the characters from Michael to displaying them in an array.

file.txt: 
8 
Michael

im using inputFile >> integer, from there i need that integer to use to make this array char mike[integer];, then i can read in the chars to the array

2条回答
手持菜刀,她持情操
2楼-- · 2019-03-06 05:51

To answer your question:

#include <fstream>
using namespace std;

int main() {
    ifstream f("file.txt");
    int n;
    f >> n;
    char chs = new char[n];
    for (int i = 0; i < n; ++i) f >> chs[i];

    // do something about chs

    delete [] chs;
}

But, I would go with (if your Michael appears on its own line):

#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream f("file.txt");
    int n;
    f >> n;
    string str;
    getline(f, str);
}
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-03-06 05:51
#include <fstream.h>
#include <string.h>

int main() 


    {
        ifstream f("file.txt",ios::in);
        int n;
        f >> n;
        char string[n];
        f.getline(string,n);
       cout<<string;

    }

This gives output off the following string in file.txt.

查看更多
登录 后发表回答