簡體   English   中英

嘗試輸入雙精度向量時出現奇怪的錯誤

[英]Weird error when attempting to input a vector of doubles

我在輸入參與者時間時遇到了很大的問題。

在終端中,它應該如下所示:

Enter participants:
Kalle Svensson Glommen IK
Anna Nilsson Glommen IK
Per-Erik Jonsson Tuna OK
DONE
Times Kalle: 12.34 10.01 -1.00
Times Anna: 8.05 9.57 10.00 12.34 -1.00
Times Per-Erik: 10.44 -1.00
 Surname   First name     Club: Times
==========================================
 Nilsson Anna Glommen IK: 8.05 9.57 10.00 12.34
 Svensson Kalle Glommen IK: 10.01 12.34
 Jonsson Per-Erik Tuna OK: 10.44

這是我的代碼:


#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

struct Runner_Type
{
  string first_name;
  string surname;
  string club;
  string club_last;
  vector<double> time;
  
};

using Many_Runners_Type = vector<Runner_Type>;


void print(Runner_Type const & runner)

{
  cout << setw(9) << runner.surname << setw(10) << runner.first_name << setw(13) << runner.club << setw(3) << runner.club_last;

}


void print(Many_Runners_Type const & many_runners)
{
  for (Runner_Type const & runners : many_runners)
    {      
      print(runners);
      cout << endl;
    }
}


int main()
  
{
  Runner_Type runner {};
  Many_Runners_Type many_runners {};
  string name {};
  int counter {};
  double tid {};



  cout << "Enter participants: " << endl;

  while (true)
    
    {
      cin >> name;

      counter++;

      if (name == "DONE")

    {
      break;
    }

      runner.first_name = name;

      cin >> runner.surname >> runner.club >> runner.club_last;
      many_runners.push_back(runner);
      
    }

  for (int i {}; i < counter; ++i)
    {
      cout << "Times " << many_runners.at(i).first_name << ": ";

      while (tid != -1.0)
    {
      cin >> tid;
      runner.time.push_back(tid);
    }

    }

  cout << "Surname" << setw(11) << "First name" << setw(23) << "Club: Times" << endl;
  cout << "==========================================" << endl;


  print(many_runners);
  cout << endl;


  return 0;
}

我可以輸入參與者的姓名,但是當我嘗試輸入時間時,它不起作用。 如果輸入為-1.0,我嘗試做一個跳出循環的循環。

這是我的終端的樣子:

Enter participants: 
Cebu Jonsson FC Barcelona
DONE
Times Cebu: 12.12 14.12 -1 

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check: __n (which is 1) >= this->size() (which is 1)
Aborted (core dumped)

為什么我會收到此錯誤? 我的程序確實符合,但是當我運行它時,輸入時間並以“-1”結尾,我得到了這個奇怪的錯誤。 非常感謝幫助

您將counter增加一次太多,即當輸入DONE時,您不應該增加。 所以你讀過了向量的結尾。 正如評論中所建議的,我會省略計數器並查詢向量的.size()

暫無
暫無

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

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