• 9
• 10
• 10
• 9
• 10

# C++ open txt file and iterate through lines to find \n character to delete it

This topic is 974 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi there i am trying to do comparsion that fins \n and the end of the string

problem is when i load string from a file it doesn't work i mean:

For setting str in the code it works and returns LAST CHAR IS RETURN

std::string str = "blablabla\n";
char lastChar = str.at( str.length() - 1 );
if (lastChar == '\n') ALOG("LAST CHAR IS A RETURN");

but whenever i load a file into vector<std::string> liek that:

typedef std::string AnsiString;

{

std::ifstream file(fname.c_str());
if (file.good() == false) {
file.close();
return;
}

AnsiString str;

Count = 0;
if (Strings.size() > 0) Strings.clear();

while (std::getline(file, str))
{
Strings.push_back(str);
Count = Count + 1;
}

file.close();
}


almost all (except last one in some cases) line consists \n character but the code i use (that first one) doesn't seem to work, and since i load a text file and have there a list of other filenames  i have to manually delete \n at every line(that requres me to hit enter when i am at last line (while editing on notepad)

any idea why it doesnt find it?

##### Share on other sites

The std::getline() function uses '\n' as the default delimiter to extract a line, it discards the delimiter if it's found. You can specify a delimiter as the third argument. I'm not sure what you mean by having to manually delete the '\n' at ever line, there should be no '\n' in your strings, what does your file look like?

##### Share on other sites

file looks like:

brig/ship.spec

frigate/ship.spec

there is \n at every line end in my vector<std::string> and i have to maunally delete it

like

for (int i=0; i < s->Count; i++)
{
AnsiString str = s.Strings[i];
str.erase(str.length()-1);
}

##### Share on other sites

it seems android puts \r at the end, so i must now test whenever os puts \n or \r there, or maybe windows notepad puts \r there, anyway thanks Gooey for pointing that.

Edited by WiredCat

##### Share on other sites

This is what I typically do to trim out leading and trailing whitespace.

	//strip whitespace
const string whitespace = " \t\r\n\f\v";
//trim trailing whitespace
input.erase(input.find_last_not_of(whitespace) + 1);
input.erase(0, input.find_first_not_of(whitespace));



Works fine with any strings I've worked with, whether they contain whitespace or not, even if it's an empty string.

##### Share on other sites

it seems android puts \r at the end, so i must now test whenever os puts \n or \r there, or maybe windows notepad puts \r there, anyway thanks Gooey for pointing that.

Wiredcat, have you tried not using Windows Notepad? Replace it with notepad2 or notepad++ and always use "UTF-8 without BOM, Unix-style line endings" forever.