C++ 在C+中对流进行迭代后返回到流的开头+;

C++ 在C+中对流进行迭代后返回到流的开头+;,c++,string,file-io,ifstream,stdstring,C++,String,File Io,Ifstream,Stdstring,我用这种方法计算文件的行数 n = count(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), '\n') + 1; n=count(istreambuf_迭代器(文件),istreambuf_迭代器(),'\n')+1; 然后我想一行一行地读,但这行不通 while (!file.eof()) { string row; file >> row; cou

我用这种方法计算文件的行数

n = count(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), '\n') + 1;
n=count(istreambuf_迭代器(文件),istreambuf_迭代器(),'\n')+1;
然后我想一行一行地读,但这行不通

while (!file.eof()) {
    string row;

    file >> row;
    cout << row << endl;
}
while(!file.eof()){
字符串行;
文件>>行;
cout“我用这种方式计算文件的行数……然后我想逐行阅读”

您可以同时执行这两项操作:

std::ifstream filestream("somefile.ext");
std::vector<std::string> lines;

std::string line;
while (std::getline(filestream, line)) {
    lines.push_back(line);
}
std::cout << "file has " << lines.size() << " lines" << std::endl;
是不安全的,因为
>
可能会到达文件的结尾,或者可能会发生某些错误,因此循环体的其余部分不应依赖于正确读取。这是一个很好的方法:

std::string word;
while (file >> word) {
    ... // doing something with row
}

它实际上是逐字(而不是逐行)读取。

如果使用
ifstream
对文件进行迭代,则可以使用

e、 g:


如果您使用的是
cin
,那么它不是一个文件。因此您不能倒带它。您可以存储每一行(如@LihO建议),或者重新进行处理,以便在输入过程中循环一次,同时计算行数。

清除istream中的错误位并返回到文件的开头。这是否是实现目标的最佳方法是另一个问题,取决于您的目标

int main(int argc, char *argv[])
{
    ifstream file("file.txt");

    int n = count(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), '\n') + 1;

    file.clear();
    file.seekg(0);

    string row;    

    while (file >> row)
        cout << row << endl;

    return (0);
}
intmain(intargc,char*argv[])
{
ifstream文件(“file.txt”);
int n=计数(istreambuf_迭代器(文件),istreambuf_迭代器(),'\n')+1;
file.clear();
文件.seekg(0);
字符串行;
while(文件>>行)

cout
cin
接受控制台输入,它不会读取文件!使用
std::getline
看看是否有效。抱歉,我输入错误。这将是文件>>行。您对信息(计算行号)做了什么?seekg()有效,谢谢,但为什么建议调用clear()另外?以防在第一次通过时设置eof。大文件占用内存“不安全,因为>>可能会命中文件的结尾,或者可能会发生一些错误,因此循环体的其余部分不应依赖于正确读取它。”-实际上提取一些字符并命中eof是可以的,在没有eof的情况下获得失败状态,而不是。但是,'这是一个g好办法:没问题。
std::ifstream file(...);
int linecount = 0;
while (!file.eof()) {
    if (file.get() == '\n') { ++linecount; }
}
// Clear the eofbit.  Not necessary in C++11.
file.setstate(0);  
// Rewind to the beginning of the file.
file.seekg(0);
int main(int argc, char *argv[])
{
    ifstream file("file.txt");

    int n = count(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), '\n') + 1;

    file.clear();
    file.seekg(0);

    string row;    

    while (file >> row)
        cout << row << endl;

    return (0);
}