0

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

4
  • 1
    Learn how to use the facilities in <fstream> Commented Mar 21, 2013 at 0:54
  • It's more of a C problem. In C++ I would never use raw arrays for this. There are fancy containers and classes to hold string arrays. Commented Mar 21, 2013 at 0:55
  • Why not just put Michael in the file and read a std::string? Or are you actually only reading partial strings/lines? Commented Mar 21, 2013 at 0:57
  • i need to get the letters out of michael, so i can seperate later, therfore i need char Commented Mar 21, 2013 at 1:01

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

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
Need to check "inputFile >> integer" for failure. The statement will fail if EOF is encountered or an integer was not found.
@ThomasMatthews Well I think I just need to provide a skeleton for read in strings. As for error checking, I think we need more assumptions about the input file format and OP can do that accordingly :)
0
#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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.