I have a project where I need to reformat a plain text file.

for example,

Hello nice to meet
Glad to be here.

will be reformatted to the following:

Hello nice to meet you. Glad to be here.

how can i write a code to remove the newline character at the end of each line? This needs to be written in terms of C-strings. Thank you!

Recommended Answers

All 7 Replies

You could read each input line with the getline( ) function. That throws away newlines when encountered.

Assuming each input line ends with the newline immediately after the last nonwhitespace character, you will have to be sure to insert a space into your output before adding on the next input.

how can you exactly do that? thanks!

I would exactly do it by writing some code. Be sure to include the string library, declare your variables, and make sure the loop in which you do the reading is properly controlled.

Post your code, and someone here will then attempt to help you.

the code i have so far is:

int reformat(istream& inf, ostream& outf, int lineLength)
char newlines;
	while (inf.get(newlines))
		if (newlines != '\n')
			outf.put (newlines);
		else if (newlines == '\n')
			outf.put(' ');

	return 0;

which is incorrect. thank you!

Here's a good online reference of standard functions used in both C and C++. You can use it for future reference and confirm the following.

To use getline() with C style strings you need an istream object like cin or an ifstream object.
You also need a C style string with enough room to hold what you want read in. Then the syntax is:

streamName.getline(stringName, maxCharToReadIn, delimeter);

The default delimeter is the newline char so if that's what you want then you don't have to indicate it.

//C style string
char word[80];
cin. getline(word, 79);

means read up to 79 char into word unless the newline char is read first and terminate word with a null char.

//C style string
char word[80];
cin. getline(word, 79);

Actually, you can use the full size of the target array. The getlline( ) method will halt at size-1 characters, reserving the space for the last possible NULL terminator.

(I went for years with that same misconception about using a size one smaller than the array!)

thank you so much!!!

Be a part of the DaniWeb community

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