簡體   English   中英

為什么vector.size()在一行中讀得太少?

[英]why does vector.size() read in one line too little?

當運行以下代碼時,行數的讀取將少於實際的行數(如果輸入文件本身是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

我想我已經找到了問題的根源。 在Code :: Blocks中,一個完全空的文件將報告IDE底部狀態欄中的小控件中有1行(當前行)。 這意味着如果您實際上要輸入一行文本,那就是第1行。換句話說,Code :: Blocks通常會過度報告文件中的實際行數。 您絕對不應依賴CB或任何其他IDE來查找文件信息-這不是它們的用途。

好吧,如果文件的最后一行只是'\\ n',則不要將其壓入向量中。 如果您希望它存在,請將循環更改為:

while (getline( infile, textline, '\n' ).gcount() > 0) 
{
    if (infile.fail()) break; //An error occurred, break or do something else

    // 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";
}

使用gcount()成員檢查最后一次讀取的字符數-如果它僅讀取定界符,則將返回1。

好的,這是一個希望您能理解的解釋。 如果我們正在討論的文件不以換行符結尾,則您的代碼應該可以正常工作。 但是,如果可以呢? 假設它看起來像這樣:

"line 1"
"line 2"
""

或作為字符序列:

line 1\nline 2\n

該文件有三行-最后一行是空的,但是它在那里。 兩次調用getline之后,您已經從文件中讀取了所有字符。 對getline的第三次調用將顯示oops,文件結尾,對不起沒有更多字符,因此您只會看到兩行文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM