c++ - 为什么 vector.size() 一行读得太少了?

标签 c++ count lines

运行以下代码时,读取的行数将少于实际行数(如果输入文件本身是 main 文件,否则) 这是为什么?我该如何改变这个事实(除了只加 1)?

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    // open text file for input
    string file_name;

    cout << "please enter file name: ";
    cin  >> file_name;

    // associate the input file stream with a text file
    ifstream infile(file_name.c_str());

    // error checking for a valid filename
    if ( !infile ) {
        cerr << "Unable to open file "
             << file_name << " -- quitting!\n";
        return( -1 );
        }
        else cout << "\n";

    // some data structures to perform the function
    vector<string> lines_of_text;
    string textline;

    // read in text file, line by line
    while (getline( infile, textline, '\n' ))   {
        // add the new element to the vector
        lines_of_text.push_back( textline );

        // print the 'back' vector element - see the STL documentation
        cout << "line read: " << lines_of_text.back() << "\n";
    }
cout<<lines_of_text.size();
    return 0;
}

最佳答案

您的代码是正确的。这是一个可能有帮助的小测试用例:

void read_lines(std::istream& input) {
  using namespace std;
  vector<string> lines;
  for (string line; getline(input, line);) {
    lines.push_back(line);
    cout << "read: " << lines.back() << '\n';
  }
  cout << "size: " << lines.size() << '\n';
}

int main() {
  {
    std::istringstream ss ("abc\n\n");
    read_lines(ss);
  }
  std::cout << "---\n";
  {
    std::istringstream ss ("abc\n123\n");
    read_lines(ss);
  }
  std::cout << "---\n";
  {
    std::istringstream ss ("abc\n123");  // last line missing newline
    read_lines(ss);
  }
  return 0;
}

输出:

read: abc
read: 
size: 2
---
read: abc
read: 123
size: 2
---
read: abc
read: 123
size: 2

关于c++ - 为什么 vector.size() 一行读得太少了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2694642/

相关文章:

latex - LaTeX:LSTListing自动识别代码通过

c++ - C++中的两个运算符同时重载

c++ - cvFindContours 是如何工作的?

c++ - std::thread 和右值引用

r - 计算一行等于某个值的次数

php - 如何在回调函数中包含变量?

python - 在Python中只打印整行的一部分

C# 如何在文本文件中写入多行?

c++ - "a declaration shadows a parameter"是什么意思?

c# - 使用 C# 解析 HTML 和计数标签