C++ 从文本文件读取数据,删除所有换行符空间,并在控制台中以c++;

C++ 从文本文件读取数据,删除所有换行符空间,并在控制台中以c++;,c++,C++,//从文件中读取 fstream mfile; string word = ""; string remove_space=""; char c; //将文件中的数据连接到字符串中 mfile.open("pin.txt");//reading from the file if (mfile.is_open()) { while (!mfile.eof()) { mfile.get(c); //删除单词之间的空格,但保留换行空格 word =

//从文件中读取

fstream mfile;
string word = "";
string remove_space="";
char c;
//将文件中的数据连接到字符串中

mfile.open("pin.txt");//reading from the file
if (mfile.is_open())
{
    while (!mfile.eof())
    {
        mfile.get(c);
//删除单词之间的空格,但保留换行空格

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

cout << remove_space;
不会按您的意愿忽略换行符。每次循环到达换行符时,它都会连接到remove_空格字符串。
您必须将equals运算符:
word[i]='\n'
转换为
word[i]!='\n'
。但是,这还不够,因为if语句将检查第一个表达式,如果为true,它将忽略另一个表达式。这意味着它永远无法检查字符是否为换行符。要解决此问题,还必须反转| |运算符,如下所示:

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

为什么不一个字符一个字符地读取输入文件,只在不应忽略的情况下输出该字符呢?另外,请阅读我已经编辑了代码,现在查看它,我希望我的代码将显示在一行中,没有新行间距。我已经编辑了答案,我希望解决方案现在更清晰。您只需编写==而不是!=。我试过了,但它仍然以多行环显示代码。仅反转equals运算符是不够的,还必须翻转or运算符。再次编辑答案。我使用了or运算符,但仍然没有进展
for (int i = 0; word[i]; i++)
{
    if (word[i] != ' ' && word[i] != '\n')
        remove_space = remove_space + word[i];
}