Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 读取使用ifstream打开的文件内容_C++_Visual C++ - Fatal编程技术网

C++ 读取使用ifstream打开的文件内容

C++ 读取使用ifstream打开的文件内容,c++,visual-c++,C++,Visual C++,我在读取windows上用fstream打开的文件时遇到问题 std::ifstream file(file_name); if(!file.is_open()){ std::cerr << "file cannot be opened"; } if (!file){ std::cerr << "errors in file"; } std::vector<std::string> strings; std::string str; whil

我在读取windows上用fstream打开的文件时遇到问题

std::ifstream file(file_name);
if(!file.is_open()){
  std::cerr <<  "file cannot be opened";
}
if (!file){
  std::cerr << "errors in file";
}   

std::vector<std::string> strings;
std::string str;
while (std::getline(file, str)) {
  strings.push_back(str);
}
std::ifstream文件(文件名);
如果(!file.is_open()){
std::cerr
getline()
从输入流中提取字符,直到到达换行符或
delim
这也是一个字符,但getline并不是仅提取字符,而是丢弃删除字符。检查您的文件,查看您是否以
换行符开始,即在文件中,您不是以换行符开始的第一个,如果是

while (std::getline(file, str)) {
  strings.push_back(str);
}
将始终只迭代1次,不返回任何字符,因为它只丢弃换行符

while (std::getline(file, str) || !file.eof) {
  strings.push_back(str);
}
现在,如果它遇到了一个清除字符,还将检查是否已到达文件的结尾。

getline()
从输入流中提取字符,直到到达换行符或
delim
这也是一个字符,但getline并不是仅提取字符,而是丢弃删除字符。检查您的文件,查看您是否以
换行符开始,即在文件中,您不是以换行符开始的第一个,如果是

while (std::getline(file, str)) {
  strings.push_back(str);
}
将始终只迭代1次,不返回任何字符,因为它只丢弃换行符

while (std::getline(file, str) || !file.eof) {
  strings.push_back(str);
}

现在,如果它遇到一个清除字符,还将检查是否已到达文件结尾。

问题在于调用

std::cout << file.rdbuf();

std::cout问题在于调用

std::cout << file.rdbuf();

如果打印
strings.size(),则在while循环之后
you get zero?@NathanOliver yepIs如果文件是文本文件?是第一个字符0x1A?在Windows中,有一些特殊字符或字节值指示文件结束条件。如果文件开头包含这些字符或字节,并且您没有以二进制文件形式打开文件,Windows操作系统将返回文件结束条件。因此,在while循环之后,如果打印
strings.size()
您得到零?@NathanOliver yepIs文件是文本文件吗?第一个字符是0x1A吗?在Windows中,有特殊字符或字节值指示文件结束条件。如果您的文件在开始时包含这些字符或字节值,并且您没有以二进制方式打开文件,Windows操作系统将返回文件结束条件。原因是什么打电话?打电话的原因是什么?