Hi all. I have an assignment for class (obviously I am new to this), that requires us to read from a file and then print out the first 22 characters from each line within that file. I have tried using getline and get, but can't seem to get it to work right. Is there a way to limit the amount of symbols that 'get' reads and then move to the next line and do the same thing? Thanks so much for your help!!

I think a better approach would be just use getline to grab all of a line into a large string, then print out the first 22 characters that appear (or less if the line's not that long.)

You can (with char array type strings) limit how much input getline will read at a time, but you're faced with figuring out if there was leftover data on the line and how to get rid of it.

I think a better approach would be just use getline to grab all of a line into a large string, then print out the first 22 characters that appear (or less if the line's not that long.)

You can (with char array type strings) limit how much input getline will read at a time, but you're faced with figuring out if there was leftover data on the line and how to get rid of it.

Thanks for your suggestion, that definitely makes sense. Being as I am a newbie, how do you only print out the first 22 characters of the getline? Would you use some sort of loop to then do the same to the next lines until you have reached the end of file? Thanks again.

Yes, you could use a loop to print only up to 22 characters. Be sure to first test the length of the actual string content, and limit your loop to 22 or the string length, whichever is less.

Definitely no need of looping required.Its a simple four step procedure.

1 ) Read the entire line into the character array say str.
2 ) Check if string length of str is greater than 22 or not.
3 ) If no then cout << str ; .
4 ) If yes then str[22] = '\0' ; and then cout << str ; .

Loop through the above 4 points until end of file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.