[英]Readfile is not reading the the blank spaces from my text file?
我正在阅读一个文本文件,发现它不会在单词之间打印空白字符。 我想一次读取每个字符,然后将字符打印到输出窗口。 读取将读取文件,但不显示空格,而且我无法找出为什么跳过空格的原因。
问题:为什么读取的内容不读取测试文件中的空白字符?
当我找到一个空白字符时,我要打印单词“空白”。
码:
#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...
标准输入函数istream::operator>>()
在执行输入之前会跳过所有前导空格。 如果需要获取空间,可以使用以下两个选项:
std::noskipws
通过设置std::ios_base::noskipws
标志,流将不会丢弃前导空白,并且ch
将获得每个连续字符的值。 请注意,这仅在采用char
的重载才能成功( ch
将获得空格值)。 对于任何其他数据类型,这将不起作用:
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},
您正在执行格式化输入,请使用未格式化输入
std::fstream::traits_type::int_type ch;
while((ch = fin.get()) != std::fstream::traits_type::eof()) {
// ...
}
默认情况下,流中的operator>>
在解析值之前会跳过所有前导空格。 例如,这是使您可以读取带有int i,j,k; fin >> i >> j >> k;
的输入30 60 95
int i,j,k; fin >> i >> j >> k;
int i,j,k; fin >> i >> j >> k;
(否则,读取j
将会失败,因为在30
后面跟随一个空格,而不是整数)。
现在,如果您还想阅读空格,则有两个选择:
get()
来无格式读取字符。 fin >> std::noskipws >> ch
。 阅读有关不同iostream方法的更多信息。 特别是,您正在使用istream的operator >> 。 仔细记录其设计工作方式; 它使用空格作为定界符,并且不存储空格。
如果要读取流(例如文件流)中的每个char
,则不应使用>>
,而应考虑使用istream :: get() 。
// stream is an istream, such as cin or ifstream
char ch;
while (ch = stream.get()) { }
这对我有用。 我将其设置为一个函数,以便您可以复制粘贴。 它检测空间,以及行中的变化。 我用ASCII艺术进行了尝试,效果很好。
void print2()
{
char ch;
std::fstream myStream("GameOver.txt", std::fstream::in);
while (myStream.get(ch))
{
std::cout << ch;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.