Reading in characters and creating array c++

后端 未结 2 1451
春和景丽
春和景丽 2021-01-27 09:11

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

相关标签:
2条回答
  • 2021-01-27 09:41
    #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.

    0 讨论(0)
  • 2021-01-27 09:46

    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);
    }
    
    0 讨论(0)
提交回复
热议问题