1
fstream mfile;
string word = "";
string remove_space="";
char c;

//reading from the file

mfile.open("pin.txt");//reading from the file
if (mfile.is_open())
{
    while (!mfile.eof())
    {
        mfile.get(c);

//concatenating the data from file into string

        word = word + c;  
    }
}
for (int i = 0; word[i]; i++)
{
    if (word[i] != ' ')
        remove_space = remove_space + word[i];
}

// spaces between words are removed but newline spaces are remain

cout << remove_space;
  • Why not read the input file character by character, and only output the character if it shouldn't be ignored? – Some programmer dude Sep 28 '19 at 19:15
  • 1
    Also please read [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Some programmer dude Sep 28 '19 at 19:15

1 Answers1

1

The for loop

for (int i = 0; word[i]; i++)
{
    if (word[i] != ' ' || word[i]=='\n')
        remove_space = remove_space + word[i];
}

will not ignore the newline characters as you intend it to. Every time the loop reaches a newline character, it will be concatenated to the remove_space string.
You have to invert the equals operator: word[i] == '\n' to word[i] != '\n'. This isn't enough, however, because the if statement will check the first expression, and if it is true, it will ignore the other one. That means that it never gets to check if the character is a newline character. To solve this, you have to also invert the || operator, like so:

for (int i = 0; word[i]; i++)
{
    if (word[i] != ' ' && word[i] != '\n')
        remove_space = remove_space + word[i];
}
tonayy
  • 104
  • 1
  • 10