【问题标题】:Stream from file with <fstream>使用 <fstream> 从文件流式传输
【发布时间】:2012-02-06 00:02:23
【问题描述】:

如何在不丢失空格的情况下从文件中读取字符?
我有一个文件,其中包含例如:
快速的棕色狐狸跳过懒狗。
当我从文件中读取(一次一个字符)时,我丢失了空格,但所有其他字符都被正确读取。为什么?
这是代码示例:

unsigned int cap = (unsigned)strlen("The quick brown fox jumps over the lazy dog.");
char c[cap];
int i = 0;
while (!fIn.eof()) {
    fIn >> c[i];
    ++i;
}

for (int i = 0; i < cap; i++)
    cout << c[i];

当我打印数组时,所有空格都丢失了。你能告诉我如何避免这个问题吗?

【问题讨论】:

    标签: c++ fstream


    【解决方案1】:

    您可以使用&lt;iomanip&gt; 中声明的流操作符。

    std::noskipws 是您想要的,它指示流提取操作员不要跳过空格。

    #include <iostream>
    #include <iomanip>
    #include <fstream>
    #include <algorithm>
    
    int main()
    {
        std::ifstream ifs("x.txt");
    
        ifs >> std::noskipws;
    
        std::copy(std::istream_iterator<char>(ifs),
                  std::istream_iterator<char>(),
                  std::ostream_iterator<char>(std::cout));
    }
    

    另一种选择是使用原始输入函数fstream::get()、fstream::read()。

    【讨论】:

      【解决方案2】:

      使用“get”方法:

      ifstream in("try.in");
      char c;
      while((c = in.get()) && in) {
        cout << c;
      }
      

      【讨论】:

      • 在哪个头文件中定义了get()?
      • 为此,您需要 fstream 和 iostream。
      • (c = in.get()) 如何实际设置 c 等于下一个字符。据我了解,将其放在 while 循环中只是检查是否有另一个字符。你能解释一下吗?
      • 这是题外话。尝试阅读在线提供的信息,如果仍有不清楚的地方,请发布单独的问题
      【解决方案3】:

      默认情况下,istream 设置了 skipws(跳过空白)标志。这会在阅读时跳过前导空格。

      您可以使用 中的 std::noskipws 将其关闭

      fIn << std::noskipws;
      while (!fIn.eof()) {
          // etc.
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-04
        • 2018-08-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-15
        • 2021-11-01
        相关资源
        最近更新 更多