C++ Can';不能将整个文件读入字符串
我有一个密码:C++ Can';不能将整个文件读入字符串,c++,c++11,C++,C++11,我有一个密码: #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;
#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
和一个新行。我是一个新手,只是通过样本学习C++。我做错了什么?哇,真是鬼鬼祟祟 在上编译代码时会产生以下警告:
main.cpp:20:29: warning: the address of 'std::__cxx11::string content(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)())' will always evaluate as 'true' [-Waddress]
不再有语法歧义,内容
现在是一个实际的std::string
,一切正常
但请花一点时间来理解。谢谢:)为什么要将整数值读入
字符串中?将整数值读入整数容器不是更有意义吗?不,我想将其读入字符串作为简单的行。正如我写的,这只是为了学习。首先,文件里有什么?这些是文件中的实际字符,还是文件由恰好具有这些值的整数组成?这对文件中的实际内容有很大的不同。我只是将文件内容复制到这里。它使用UTF-8编码,但据我所知,数字代码与ASCII标准中的代码相同。@NeilButterworth,我的控制台编码有问题,因此它会向我输出一些警告,而不是正常的警告。谢谢您的详细解释。我可以得到{}
允许获得一个它是变量的编译器。但是我不明白为什么这个字符串内容((istreambuf_迭代器(文件)),istreambuf_迭代器()代码>有效,但我的无效?请你解释一下好吗?@ааcrmk_括号没有任何意义(foo
在语义上仍然等同于(foo)
),它们唯一的用途是确保语法不能是函数声明。这是因为这样一个不明确的行被定义为首先解析为一个函数声明,如果可能的话,这就是精神所在。在你的例子中,intfoo(1)但是,代码>不能是函数声明。当存在一个类型时,就会产生歧义:isintfoo(float(bar))代码>一个int
初始化为float(bar)
(bar
转换为float
),或int foo(float bar)的函数签名代码>?在声明参数时,可以将其名称用括号括起来,这样就可以同时包含两个参数。因此,选择了该函数。但是,您不能包装整个参数,因此intfoo((float(bar))代码>不能是一个函数:它不明确地是<代码> int /代码>。大多数程序员有时会碰到它,他们只是咒骂一点,加上一些括号或大括号,然后继续前进:)
main.cpp:20:29: warning: the address of 'std::__cxx11::string content(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)())' will always evaluate as 'true' [-Waddress]
string content(istreambuf_iterator<char>(file),
istreambuf_iterator<char>());
string content{istreambuf_iterator<char>{file},
istreambuf_iterator<char>{}};