C++ Characters from txt

Hi guys! Can somebody tell me how can i do this?
I have a txt file, with some sentece.
All of the sentences are 40 char long. I want to make an array.
For example: This is the first sentece.
array[1] = T
array[2] = h
array[3] = i
array[4] = s

Ty for the help :)
With it I only can get lines i think.
Or?
I think it only can do this:
Array[1] = This is the first sentence.
I think it only can do this:
Array[1] = This is the first sentence.

If you give the string the name 'array' then it will do what you need.

1
2
std::string array;
std::getline(infile, array);

each character of the string can be accessed as array[0], array[1] etc.


There are two versions of getline, having differing syntax. The above version which uses std::string is safer, as the string can resize as required. The other version, using a fixed array of characters does the same job, but requires the user take more care.
1
2
char array[100];
infile.getline(array, sizeof(array));

http://www.cplusplus.com/reference/istream/istream/getline/

You didn't say how the sentences are arranged in the text file. If each sentence is not on a line by itself, you may need to make use of the fact that the sentence ends with a '.' and use that as the delimiter in the getline(). (default is the newline character '\n').
Last edited on
If you really just want to get one character at a time... http://www.cplusplus.com/reference/istream/istream/get/

You should note that this one of the slower methods to get data out of a file, the hard drive stores data in blocks, and the computer likes to read whole blocks at a time. Reading a whole line lets it read blocks once and give you the data, reading a single char means it reads the whole block, then gives you the single character. Then it has to read the same block to get you the next, and the next, etc.

Accessing the hard drive is about 1000 times slower than accessing RAM (which is where your program is running).

There's nothing wrong with getting a single char, it's just avoided when you start thinking about optimizing your program.
Last edited on
Topic archived. No new replies allowed.