Reputation: 1
string foo ="";
ifstream openfile(argv[i+1]);//argv[i+1] is file name
if(openfile.is_open())
{
while(getline(openfile, foo))
{
istringstream myString(foo);
string w1;
while(myString >> w1)
cout<<w1<<' ';
cout <<""<< endl;
}
I need to print out the text normally, meaning no extra newlines, and no space at the end of each line.
Output:
Launch Terminal
< Words Words Words
< Words Words Words Words Words Words
<
<
< Words Words Words Words
< Words Words Words Words
< Words Words Words Words
<
<
<
<
< Words
thank you
Upvotes: 0
Views: 40
Reputation: 1329
Well, to remove the new line characters, just replace them. And to get rid of the spaces at the end of each line, don't print them, you're adding them yourself xD An example code would be
string foo;
ifstream openfile (argv[i+1]);
if(openfile.is_open())
{
while(getline(openfile, foo))
{
//Remove new line character, if any
std::replace(foo.begin(), foo.end(), '\n', '');
//Remove carraige return (windows new line is '\r\n' instead of just '\n')
std::replace(foo.begin(), foo.end(), '\r', '');
std::cout << foo; //print line
}
}
However, maybe you actually want to add a space between each line (so after you've printed foo), as otherways the first wird of one line might stick to the last of the line before, because there's nither a space nor a line break to keep them appart)
Edit: If you want to keep the original new line characters, delete the two std::replace(...)
lines in the code ;) You might also want to print an endl after you've printed foo, depending on what output you're expecting, as this is not very clear in your question
Edit2: As I got some more informations on what you actually want, here's an updated code that (at least) removes the additional spaces at the end of each line. If this still doesn't do what you want, be more clear about how the output of a specific file should look like!
string foo;
ifstream openfile (argv[i+1]);
if(openfile.is_open())
{
while(getline(openfile, foo))
{
istringstream myString(foo);
string w1;
bool firstWord=true;
while(myString >> w1)
{
if(firstWord==false)
{
cout << " ";
}
firstWord = false;
cout << w1;
}
cout << endl;
}
}
Upvotes: 1