[英]Get rid of space when printing a new line using standard output in c++ and ncurses
[英]How to get rid of new lines after printing from a text file, and get rid of ending space when printed
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;
}
我需要正常打印文本,这意味着没有多余的换行符,并且每行末尾没有空格。
输出 :
Launch Terminal
< Words Words Words
< Words Words Words Words Words Words
<
<
< Words Words Words Words
< Words Words Words Words
< Words Words Words Words
<
<
<
<
< Words
谢谢
好吧,要删除新的换行符,只需替换它们。 为了消除每行末尾的空格,请不要打印它们,而是自己添加xD。示例代码为
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
}
}
但是,也许您实际上想在每行之间添加一个空格(因此在打印foo之后),否则,一行的第一行可能会粘到行的最后一行,因为那里没有空格或换行符了保持他们的意愿)
编辑:如果要保留原始换行符,请删除代码中的两行std::replace(...)
;)您可能还希望在打印foo之后打印endl,具体取决于输出内容您正在期待,因为您的问题并不十分清楚
Edit2:随着我获得了有关您实际想要的更多信息,这是一个更新的代码(至少)删除了每行末尾的额外空格。 如果仍然不能满足您的要求,请更加清楚特定文件的输出外观!
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.