为什么在写入文件时删除空白 space 无法读取文件?
why does removing blank space while writing into file fails reading files?
我正在学习 C++,如果我在写入文件时没有添加空白 space,我发现读取文件时会出现问题。
此外,我写入的文件不包含预期的空白 space。(我用记事本++打开它)
顺便说一句,我正在使用 code::blocks17.12.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{ ofstream out("file1");
int i;
ifstream in;
if(!out){cerr << "create file error!\n"; return 1;}
for(i = 1; i<=10; ++i) out << i <<' ';
/*if I remove (<<' ') here, nothing was pirnted on screen. */
out.close();
in.open("file1");
if(!in){cerr << "open file error!\n"; return 1;}
while(in >> i) cout<< i << ' ';
in.close();
return 0;
}
如果你将 1
、3
和 8
写入一个没有 space 的文件,那么你会得到 138
你现在想如何计算原来写的不是138
?
输入流需要某种数字分隔方式的指示。
如果你想知道为什么他们决定写一个数字不会自动添加一个 space,那是因为它并不总是需要的行为。
正如 Martin Heralecký 正确提到的那样。 in >> i
没有读入任何内容,因为没有 space 就将 12345678910
写入文件,这肯定超出了 int
只有您的设置的范围。
int
的实际大小是 platform-dependent,但您不应期望它可以存储大于 2147483647
的数字。
的更多详细信息
我正在学习 C++,如果我在写入文件时没有添加空白 space,我发现读取文件时会出现问题。
此外,我写入的文件不包含预期的空白 space。(我用记事本++打开它)
顺便说一句,我正在使用 code::blocks17.12.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{ ofstream out("file1");
int i;
ifstream in;
if(!out){cerr << "create file error!\n"; return 1;}
for(i = 1; i<=10; ++i) out << i <<' ';
/*if I remove (<<' ') here, nothing was pirnted on screen. */
out.close();
in.open("file1");
if(!in){cerr << "open file error!\n"; return 1;}
while(in >> i) cout<< i << ' ';
in.close();
return 0;
}
如果你将 1
、3
和 8
写入一个没有 space 的文件,那么你会得到 138
你现在想如何计算原来写的不是138
?
输入流需要某种数字分隔方式的指示。
如果你想知道为什么他们决定写一个数字不会自动添加一个 space,那是因为它并不总是需要的行为。
正如 Martin Heralecký 正确提到的那样。 in >> i
没有读入任何内容,因为没有 space 就将 12345678910
写入文件,这肯定超出了 int
只有您的设置的范围。
int
的实际大小是 platform-dependent,但您不应期望它可以存储大于 2147483647
的数字。