remove beginning and end whitespace

hi heys, i am trying to remove beginning and the end whitespace in one file, and output the result to another file. But i am confused about how to remove whitespace. i need to make a function to do it. It should use string, anyone can help me ?
here is my code.

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>

using namespace std;
void IsFileName(string filename);

int main(int argc, char const *argv[]) {
string inputfileName = argv[1];
ifstream inStream;
inStream.open("first.txt");
IsFileName(inputfileName);

string outputfileName = argv[2];
ofstream outStream;
outStream.open("second.txt");
IsFileName(outputfileName);

string line;
while (getline(inStream, line))
{
cout << line << endl;
outStream << line <<endl;
}

inStream.close();
outStream.close();

/*add code*/
return 0;
}// main

void IsFileName(string filename){
ifstream inStream;
inStream.open(filename.c_str());
if (inStream.fail()){
cout << "Error opening the file"<<endl;
exit(0);
}
}
You are multiply confused. You appear to try to open two input files: one in main() and the other via a function. You do nothing with the latter. Similarly with output.

Please explain more clearly exactly what white space you are trying to remove.

Please use code tags when posting code.
Here is a simple trim routine. if you want to keep all the internals instead, you can replace that bit with a substring and it would be simpler and faster. I am sure it can be made better; as I said, it is a quick/simple one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

void trim(string &s, char c, bool keepinternal = true)
{  //keepinternal true means keep one copy of multiples inside 
//while false means to remove all copies.  ALL leading and trailing (even multiples)
//are removed regardless. 
  size_t dx; size_t i; size_t j; 
  if(keepinternal == false)
  { //completely eliminates the character c from the string.   
  	s.erase(std::remove(s.begin(), s.end(), c), s.end());
	return;
  }  
  //trim leading and trailing and internal
  dx = 0;   i = s.length()-1;   
  while(s[dx] == c) {dx++;} //find the first letter that is not c
  while(s[i] == c) {i--;} //find the last letter that is not c  
  string temp = s;  s = ""; //copy s into temp and set s to empty string
  for(j = dx; j<i+1; j++)
  { //for all the letters between the first not c up to the last not c, copy back into s
    //unless there are 2+ in a row, then only get the first one. 
	if(temp[j]!=c || (temp[j]==c && temp[j+1]!=c))//keeps 1 copy per group of 1 or more cs internally
	s += temp[j]; 
  }
}
Last edited on
Topic archived. No new replies allowed.