从C++中带空格的文件中读取

Aar*_*ron 0 c++ arrays ifstream

我正在从一个文件中读取并将数组(指针)的前面传递回我的main函数.我遇到的问题是它没有复制单词之间的空格.例如,Hello Hello出来HelloHello.

我开始使用getLine而不是遇到了文件大小的问题.我将其设置为500,因为没有文件大于500,但大多数文件将低于500,我试图获得文件的确切大小.

这是我的代码:

char infile()
{
   const int SIZE=500;
   char input[SIZE];
   char fromFile; 
   int i=0;

   ifstream readFile;
   readFile .open("text.txt");
   while(readFile>>fromFile)
   {
     input[i]=fromFile;
     i++;
   }
   cout<<endl;
   returnArray=new char[i];//memory leak need to solve later
   for(int j=0;j<i;j++)
   {
      returnArray[j]=input[j];
      cout<<returnArray[j];
    }
    cout<<endl;
  }
  return returnArray[0];
}
Run Code Online (Sandbox Code Playgroud)

Geo*_*sov 5

根据您的文件格式,您可能希望使用ifstream::read()ifstream::getline()替代.

operator >>尝试在数据流被读取时"标记"或"解析"数据流,使用空格作为标记之间的分隔符.您有兴趣从原始数据中获取原始数据,因此您应该避免使用它.如果要一次读取一行数据,使用换行符作为分隔符,则应使用getline().否则使用read().