C++ 通过ifstream读取文件时std::getline失败
我创建了这段代码(使用C++11标准): 但是,当我运行它时,它已成功编译:C++ 通过ifstream读取文件时std::getline失败,c++,c++11,gcc,C++,C++11,Gcc,我创建了这段代码(使用C++11标准): 但是,当我运行它时,它已成功编译: Enter the name of a file: example.txt Reading file... 然后什么也没有。它不输出文件的任何字符。文件确实存在,并且打开它没有任何问题。但是,当我编译并运行此代码时: #include <iostream> #include <fstream> #include <string> using namespace std; int m
Enter the name of a file:
example.txt
Reading file...
然后什么也没有。它不输出文件的任何字符。文件确实存在,并且打开它没有任何问题。但是,当我编译并运行此代码时:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string input;
cout << "Enter the name of a file:\n";
getline(cin, input);
cout << "Reading file...\n";
ifstream readstream(input);
if (!readstream.is_open()) {
cout << "Error while opening file\n";
return 0;
} else {
char currentchar;
while (!readstream.eof()) {
while(readstream.get(currentchar)) {
cout << currentchar;
}
}
return 0;
}
}
但是我没有使用getline(),而是使用了ifstream.get()
有人能告诉我为什么getline()在这种情况下不起作用吗 “它成功地编译了”——我真诚地怀疑这一点。也许可以指出
std::getline
的具体重载,您认为应该使用while(getline(readstream,currentchar))执行。简短回答:没有使用char
作为第二个参数的std::getline
重载。例如,您试图调用一个不存在的函数。@WhozCraig啊,好的。那是我打字时的一个错误。我会解决的。但即使我使用字符串而不是字符,它也会失败。我怀疑文件中没有任何尾行字符。。。但这只是一个新的想法,这段代码要求在您的环境中使用调试器。我看不出你说的代码有什么明显的错误。假设您的输入文件名是一个文本文件,可以从您提供的任何相对或绝对路径(如果有的话)访问,它应该可以工作。调试器和单步执行是您最好的下一步。我尝试了您的第一个代码,效果很好。example.txt看起来像什么?“它编译成功了”-我真诚地怀疑这一点。也许可以指出std::getline
的具体重载,您认为应该使用while(getline(readstream,currentchar))执行。简短回答:没有使用char
作为第二个参数的std::getline
重载。例如,您试图调用一个不存在的函数。@WhozCraig啊,好的。那是我打字时的一个错误。我会解决的。但即使我使用字符串而不是字符,它也会失败。我怀疑文件中没有任何尾行字符。。。但这只是一个新的想法,这段代码要求在您的环境中使用调试器。我看不出你说的代码有什么明显的错误。假设您的输入文件名是一个文本文件,可以从您提供的任何相对或绝对路径(如果有的话)访问,它应该可以工作。调试器和单步执行是您最好的下一步。我尝试了您的第一个代码,效果很好。example.txt看起来像什么?
Enter the name of a file:
example.txt
Reading file...
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string input;
cout << "Enter the name of a file:\n";
getline(cin, input);
cout << "Reading file...\n";
ifstream readstream(input);
if (!readstream.is_open()) {
cout << "Error while opening file\n";
return 0;
} else {
char currentchar;
while (!readstream.eof()) {
while(readstream.get(currentchar)) {
cout << currentchar;
}
}
return 0;
}
}
g++ -std=c++11 read.cpp -o read.exe