c++ - Readfile is not reading the the blank spaces from my text file? -


i reading in text file , have found not print blank characters between words. want read each character character @ time , print character output window. read read file not show blank spaces , have not been able find out why blank spaces being skipped.

question: why read not reading blank characters in test file?

when find blank character want print word blank space.

code:

#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 blank spaces           {               std::cout << "blank space" << std::endl;           }           else  <-- write letter           {               std::cout << ch << std::endl;            }     } }  int _tmain(int argc, _tchar* argv[]) {    readtestfile();     getchar();    return 0; } 

test file:

  testing fprintf...   testing fputs... 

output

 letter: t  t  letter: h  h  ...etc... 

the standard input function istream::operator>>() skips leading whitespace before performing input. if need obtain spaces, there couple options can use:

  • std::noskipws

    by setting std::ios_base::noskipws flag, stream not discard leading whitespace , ch given value of each consecutive character. note succeeds overload takes char (ch given value of space). other data type not work:

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

    get() unformattedinputfunction function, , not parse input beforehand.

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

    you can use iterators work directly buffer. std::istreambuf_iterator<> doesn't parse input:

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

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -