编辑:已解决。将ins >> val
移动到循环之前,然后将ins.fail()
作为条件。我不完全确定为什么这会有所帮助,但确实如此,我很乐意继续前进。
原帖:
我遇到了以下代码的问题。由于某种原因,它读入file.txt
并返回为好,但istream正在读取输入,好像文件是空白的。作为参考,我在Xcode工作。我试过玩这个计划,但似乎没什么用。我只是不明白它是如何在文件中成功读取的(我在一些...
代码中运行检查并且它说文件已成功打开)但是却没有提取任何输入。
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream inFile;
inFile.open("file.txt");
// There exists a class called Position that isn't important for
// this but just clarifying
Position pos;
pos.read(inFile);
return 0;
}
void Position::read(istream& ins) {
int val;
char discard;
while (!(ins >> val)) {
ins.clear();
ins >> discard;
}
}
我对此比较陌生,现在只编写了大约6个月。我非常感谢任何解释。谢谢大家!
编辑:此代码的意图是以int的形式从文件中提取输入。如果输入不是int
,则循环将重置为良好状态并将非int作为char
拉入。我不太关心文件的实际文本似乎正在消失的事实。代码主要是为了一些上下文而提供的。
抱歉我不熟悉Stack!
edit2:如果我像这样运行循环:
while (!(ins >> val)) {
ins.clear();
ins >> discard;
cout << discard;
}
它进入无限循环,因为文件没有输入。我不确定如何为此显示I / O,因为问题是没有任何输入,因此没有输出。当我测试时,它只是运行并运行并运行直到我停止它。实际的.txt文件不是空的,但它在某种程度上被视为是。
edit3:添加更多行以尝试澄清究竟发生了什么。
再次感谢!
这是一个简短的例子,显示:
我希望它澄清事情。这个问题有点难以直接回答,因为你永远不会解释ins
是什么。
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using std::string;
using std::ifstream;
using std::ofstream;
using std::vector;
void append_to_file(string const& filename, string const& text)
{
// Open the file in append mode
ofstream file(filename, std::ios_base::app);
// Write the text to the file
file << text;
}
void write_to_file(string const& filename, string const& text)
{
// Clear the file and open it
ofstream file(filename);
file << text;
}
// Read all the lines in the file
vector<string> read_all_lines(string const& filename)
{
ifstream file(filename);
vector<string> lines;
while(not file.eof() && not file.fail()) {
// Get the line
std::string line;
std::getline(file, line);
// Add the line into the vector
lines.push_back(std::move(line));
}
return lines;
}
int main()
{
string filename = "test-file.txt";
// Clear the file and write
write_to_file(filename, "This is a sentence.\n");
// Append some additional text to the file:
append_to_file(filename, "This is some additional text");
// Read all the lines in the file we wrote:
vector<string> lines = read_all_lines(filename);
// Print the lines we read:
for(auto& line : lines) {
std::cout << line << '\n';
}
}