Readfile不是从我的文本文件中读取空格?

时间:2014-03-24 20:28:38

标签: c++

我正在阅读一个文本文件,并发现它不会打印单词之间的空白字符。我想一次读取每个字符一个字符,然后将字符打印到输出窗口。读取将读取文件,但不显示空格,我无法找出为什么跳过空格。

问题:为什么我的阅读没有读取测试文件中的空白字符?

当我找到一个空白字符时,我想打印空白一词。

代码:

#include "stdafx.h"
#include "iostream"
#include<iostream>
#include<fstream>

void readTestFile()
{
    char ch;
    std::fstream fin("C:/Users/itpr13266/Desktop/myTest.txt", std::fstream::in);
    while (fin >> ch) {
        std::cout << "Letter: " << ch << std::endl;
          if (ch == ' ')  <-- should catch a blank spaces
          {
              std::cout << "Blank Space" << std::endl;
          }
          else  <-- Just write the letter
          {
              std::cout << ch << std::endl; 
          }
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
   readTestFile();

   getchar();
   return 0;
}

测试文件:

  This is testing for fprintf...
  This is testing for fputs...

输出

 Letter: T
 T
 Letter: h
 h
 ...etc...

5 个答案:

答案 0 :(得分:3)

标准输入函数istream::operator>>()在执行输入之前跳过所有前导空格。如果您需要获得空格,可以使用几个选项:

  • <强> std::noskipws

    通过设置std::ios_base::noskipws标志,流不会丢弃前导空格,ch将被赋予每个连续字符的值。请注意,只有在charch将被赋予空间值的重载时才能成功。对于任何其他数据类型,这将不起作用:

    while (fin >> std::noskipws >> ch)
    {
        // ...
    }
    
  • <强> std::istream::get()

    get()是UnformattedInputFunction函数,因此不会事先解析输入。

    while (fin.get(ch))
    {
        // ...
    }
    
  • <强> std::istreambuf_iterator<>

    您还可以使用迭代器直接使用缓冲区。 std::istreambuf_iterator<>也不解析输入:

    std::copy(std::istreambuf_iterator<char>{fin},
              std::istreambuf_iterator<char>{},
              std::ostreambuf_iterator<char>{std::cout},
    

答案 1 :(得分:1)

您正在执行格式化输入,使用未格式化的输入

std::fstream::traits_type::int_type ch;
while((ch = fin.get()) != std::fstream::traits_type::eof()) {
    // ...
}

答案 2 :(得分:0)

默认情况下,流上的operator>>会在解析值之前跳过任何前导空格。例如,这是允许您使用30 60 95读取输入int i,j,k; fin >> i >> j >> k;的原因(否则读取j会失败,因为在30之后,会出现空格,而不是整数)。

如果您想要阅读空格,现在有两个选项:

  1. (首选):使用成员函数get()进行无格式读取字符。
  2. 在阅读之前,请指示流不要吃空格:fin >> std::noskipws >> ch

答案 3 :(得分:0)

详细了解不同的iostream方法。特别是,您正在使用istream's operator>>。仔细注意它的工作原理;它使用空格作为分隔符,不存储空格。

如果您想要从流中读取每个char(例如文件流),则不应使用>>,而应考虑使用istream::get()

// stream is an istream, such as cin or ifstream
char ch;
while (ch = stream.get()) { }

答案 4 :(得分:0)

这对我有用。我在一个函数中设置它,以便您可以复制粘贴。它可以检测空间,也可以检测线的变化。我用ASCII艺术试过它,效果很好。

void print2()
    {
    char ch;
    std::fstream myStream("GameOver.txt", std::fstream::in);
    while (myStream.get(ch))
        {
            std::cout << ch;        
        }
    }