【发布时间】:2014-05-02 10:19:29
【问题描述】:
我正在阅读一个文本文件,发现它不会打印单词之间的空白字符。我想一次读取每个字符一个字符,然后将字符打印到输出窗口。读取将读取文件但不显示空格,我无法找出跳过空格的原因。
问题:为什么我的 read 没有读取测试文件中的空白字符?
当我找到一个空白字符时,我想打印空格这个词。
代码:
#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...
【问题讨论】:
-
您的示例输出甚至没有显示问题。当它到达第一个空间时会发生什么?也可以打印出
ch的整数值。 -
此操作
fin >> ch解析空白。它故意不抓取空格。
标签: c++