为什么filestream不把空白写入文件cpp ?

Why wont filestream write whitespaces into files cpp?

本文关键字:文件 cpp 空白 filestream 为什么      更新时间:2023-10-16

我有一个CPP代码

 #include<iostream>
 #include<fstream>
 #include<string>
  using namespace std;
  int main()
 {
    string s,s1;
    ofstream f("new.txt");
     cin>>s;
     f<<s;
    f.close();
    ifstream f1("new.txt");
    while(!f1.eof())
    {
     f1>>s1;
     cout<<s1;
    }
 return 0;
  }

如果我给输入字符串作为"MAGICAL string WITH SPACES"。ofstream对象只将"MAGICAL"写入文本文件,我该如何从字符串变量中写入和读取空白到输出文件流中呢?

这是因为您使用了cin。试试getline()吧!

string newArgument = "";
getline(cin, newArgument);