Hello,
I'm trying to complete a problem that asks to print out the first 50 spaces of each line. I can print out the whole file, but I don't know how to print the first 50 spaces. Any help will be greatly appreciated.
Correction: I need to print the words in the first 50 spaces.
Instead of reading the file in binary mode, read it in text mode so that you can read 1 line into a string. Then loop until the file is processed. For each line that is read into the string, print the lesser of the number of characters in the line or the first 50 characters. From what you are describing it seems that you are working with a text file, not a binary file.
i understand how to use string and getline function, but I don't know how to manipulate it to print the first 5o characters. How do I read a line into a string?
Is text mode just removing the ios::binary from the code?
Your while loop is on the write track. After reading each line, you have to determine the string size. The string::size function tells you that. Or you could simply do another loop until 50 characters are printed or the end of the string is reached. Put this loop inside your do..while and get rid of your cout.write statement.
int main ()
{
string inputBuffer;
ifstream fin;
fin.open ("trekkie.txt");
do {
int current(0);
getline(fin, inputBuffer);
while(current < 50 && current < inputBuffer.size())
{
cout << inputBuffer[current++];
}
cout << endl;
} while (!fin.eof());
fin.close();
return 0;
}
What I had posted before was just the general idea. You actually have to initialize the current variable prior to using it and increment it within the loop. Beginners need to realize that many times we are just posting hints to get you going but you do have to use a little common sense when incorporating those ideas into your program.
By the way, I tried this with a two line text file containing:
This line is less than 50 characters.
This line is definitely going to contain a lot more than 50 characters.