我假设这里的每个人都熟悉所有文本文件应以换行符结尾的格言.多年来我一直都知道这个"规则",但我一直在想 - 为什么?
我刚刚在这个答案中发现了一条评论说iostream::eof在循环条件下使用"几乎肯定是错误的".我通常使用类似的东西while(cin>>n)- 我猜是隐式检查EOF,为什么检查eof显式使用while (!cin.eof())错误?
它与scanf("...",...)!=EOF在C中使用有何不同(我经常使用没有问题)?
我正在尝试编写一个函数,它将检测我几乎在字符串流的末尾,但它似乎不起作用.
这是一些代码:
std::string path(1.2.3);
int number;
std::stringstream ss(path);
while (!ss.eof()) {
if (ss.peek() != '.') {
ss >> number;
if (ss.tellg() == path.length()) {
std::cout << "Last one: " << number;
} else {
std::cout << number;
}
} else { ss.get(); }
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用ss.tellg()== path.length(),但这不起作用.有人有替代方案吗?
假设我们有一个简单的流:
hello
Run Code Online (Sandbox Code Playgroud)
请注意,\n文本文件中通常没有额外的内容.现在,以下简单代码显示eof在提取单个数据后在流上设置该位std::string.
int main(int argc, const char* argv[])
{
std::stringstream ss("hello");
std::string result;
ss >> result;
std::cout << ss.eof() << std::endl; // Outputs 1
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,我不明白为什么会根据标准发生这种情况(我正在阅读C++ 11 - ISO/IEC 14882:2011(E)).operator>>(basic_stream<...>&, basic_string<...>&)被定义为表现得像格式化的输入函数.这意味着它构造了一个sentry对象,它继续吃掉空白字符.在这个例子中,没有,所以sentry构造完成没有问题.转换为a时bool,sentry对象给出true,因此提取器继续继续实际提取字符串.
然后将提取定义为:
提取并附加字符,直到出现以下任何一种情况:
n字符存储;- 文件结束发生在输入序列上;
isspace(c,is.getloc())对于下一个可用的输入字符c,则为true .在提取最后一个字符(如果有)之后,调用is.width(0)并销毁sentry对象k.如果函数没有提取任何字符,则会调用
is.setstate(ios::failbit),这可能会抛出ios_base::failure(27.5.5.4).
这里没有任何东西实际上导致该eof位被设置.是的,如果提取到达文件结尾,则提取停止,但它不会设置该位.事实上,eof只有当我们做另一个时才应该设置该位ss >> result;,因为当sentry …
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
using namespace std;
int main()
{
string temp;
ifstream inFile;
ofstream outFile;
inFile.open("ZRMK Matched - 010513.txt");
outFile.open("second.txt");
while(!inFile.eof()) {
getline(inFile, temp);
if (temp != "") {
getline(inFile, temp);
outFile << temp;
}
}
cout << "Data Transfer Finished" << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我很难让这个工作.当我执行程序时,它会循环一段时间,然后终止而不完成 - 它不会向输出文件输出任何文本行.任何帮助,将不胜感激.
c++ ×4
iostream ×2
string ×2
c++-faq ×1
file ×1
newline ×1
stringstream ×1
text-files ×1
unix ×1