【发布时间】:2017-04-30 23:27:08
【问题描述】:
我有一个代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
ifstream file;
do {
string filename;
cout << "Input file name:" << endl;
cin >> filename;
file.open(filename, ios::in);
} while (!file.is_open());
string content(istreambuf_iterator<char>(file),
istreambuf_iterator<char>());
cout << "Content:\n" << content << endl;
if (file.is_open()) {
file.close();
}
return 0;
}
要读取此文件内容:
1 -1 0 -3 0
-2 5 0 0 0
0 0 4 6 4
-4 0 2 7 0
0 8 0 0 -5
但它只输出1 和一个新行。
附:我是个菜鸟,只是通过示例学习 C++。我做错了什么?
【问题讨论】:
-
为什么要将整数值读入
string?将整数值读入整数容器不是更有意义吗? -
不,我想将它作为简单的行读入
string。正如我所写,它仅供学习。 -
首先,那个文件里有什么?这些是文件中的实际字符,还是文件由恰好具有这些值的整数组成?这对于文件中的实际内容有很大的不同。
-
刚才我复制了一个文件内容到这里。它使用 UTF-8 编码,但据我所知,数字代码与 ASCII 标准中的代码相同。
-
@NeilButterworth,我的控制台编码有问题,所以它会输出一些警告而不是正常警告。