这里是从A C A片断++教程:为什么在这里检查两次C++输入文件流?
// istream::get example
#include <iostream> // std::cin, std::cout
#include <fstream> // std::ifstream
int main() {
char str[256];
std::cout << "Enter the name of an existing text file: ";
std::cin.get (str,256); // get c-string
std::ifstream is(str); // open file
while (is.good()) // loop while extraction from file is possible
{
char c = is.get(); // get character from file
if (is.good())
std::cout << c;
}
is.close(); // close file
return 0;
}
通知is.good()
与while
出现两次,第一次,然后用if
。
链接到例如:http://www.cplusplus.com/reference/istream/istream/get/
这是C++中文件I/O的一个不好的例子。我不会推荐你找到这个程序的教程。 – 0x499602D2
谨慎地阐述为什么? – jia103
您应该在执行输入后检查输入是否成功。 'while'循环中的条件是在输入实际发生之前检查流是否为'good()'*。而且,'std :: string'是操作动态大小的字符串的首选结构,而不是需要使用'.get()','.getline()'等古代输入方法的C-style字符串,和他们各自的过载。 – 0x499602D2