Hi,I want to ask how it is possible to read a file without printing newlines?
I'm using getline() to read the strings but I want to print all the strings consecutively even if they've been seperated in the file with a new line.

Recommended Answers

All 5 Replies

getline() does not add the new line character to the end of the string, so if you display the string don't add endl or '\n' after it.

I haven't used endl or '\n'.You know when I'm reading the first line of my file I just want to print 80 characters of it in the first line of my output, then the rest of the first line of file is printed in the next line but as I'm going to print the second line of the file in continue of my output file it goes to a new line.
and this is my code:

while (!f.eof()){
		for (int w=0;w<Line();w++){
			M=0;
			while (M<=80){
				getline (f,s,' ');
				const char* p1=s.c_str();
				cout<<p1<<" ";
				M=strlen(p1)+1+M;
			}
			}
		}

This is one way to print only 80 characters on a line. I'm sure it could be better optimized, but I just don't feel like taking the time to do it. And it does not do word wrap like an editor would do, then 80 characters is met it just goes to the next line. If you want word wrap then you won't get 80 characters on every line without doing other fancy stuff, such as adding extra spacing between some words to force 80 characters (like newspaper print columns).

int LineLength = 0;
while( getline(f,s) )
{
   for(int i = 0; i < s.length(); i++)
   {
       cout << s[i];
       LineLength++;
       if( LineLength == 80)
       {
          cout << '\n';
          LineLength = 0;
       }
    }
}

@OP, why is your code so bad? I don't know what you need, but how about something like
this :

string aLine;
const int MAX_PRINT_CHAR = 80;
getline(fileIn,aLine){
 if(aLine.size() < MAX_PRINT_CHAR ) cout << aLine << endl;
 //else print the first MAX_PRINT_CHAR characters and then print the rest in a different line
 else cout << aLine.substr(0,MAX_PRINT_CHAR) << endl << aLine(MAX_PRINT_CHAR);
}

@firstPerson: that only works if the length of the string < 160 characters, and the cursor is at the beginning of the line. It won't work if there is already some text on the line.

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.