前提・実現したいこと
C++を用いて自動採点のシステムを開発しているのですが、
out_of_rangeの例外がどこから発生して、どう処理したらいいのかが分かりません。
今度はデータが正しく出力されない問題が発生しました…
発生している問題・エラーメッセージ
~~terminate called after throwing an instance of 'std::out_of_range'what(): basic_string::substr: __pos (which is 4) > this->size() (which is 0)This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
~~
該当のソースコード
C++
1#include <iostream> 2#include <fstream> 3#include <string> 4#include <vector> 5#include <utility> 6#include "AnswerCheck.h" 7 8typedef vector<string> Type; 9 10Type answer; 11 12Type putdata(string s){ 13 int cnt = 0, pnt = 0, cha = 0; 14 Type buf; 15 16 while(1){ 17 if(buf.size() == 13) break; 18 if(s[cha] != ','){ 19 cnt++; 20 } 21 else{ 22 ** try{ 23 buf.push_back(s.substr(pnt + 1, cnt - 2)); 24 } 25 catch(...){ 26 buf.push_back(""); 27 } 28 pnt += ++cnt; 29 cnt = 0; 30 } 31 cha++; 32 } 33 34 return buf; 35} 36 37int main(void){ 38 ifstream ifs("data.csv"); 39 ofstream log("log.csv", ios::trunc); 40 int cnt = 0; 41 42 log << "Class,Number,A1,A2,A3,A4,A5,B1,B2,B3,B4,B5,B6,A Result,Sum Result" << endl; 43 44 string s; 45 while(getline(ifs, s)){ 46 int a_result = 0, result = 0; 47 if(cnt != 0){ 48 Type buf = putdata(s); 49 string id = buf[1]; 50 pair<string, string> user; 51 user.first = id.substr(4, 1); 52 user.second = id.substr(5, 2); 53 cout << "Class : " << user.first << endl 54 << "Number : " << user.second << endl; 55 log << user.first << "," 56 << user.second << ","; 57 for(int a = 2; a < buf.size(); a++){ 58 int score = check(buf[a], a - 2); 59 result += score; 60 if(a < 7) a_result += score; 61 log << score << ","; 62 } 63 log << a_result << "," << result << flush << endl; 64 } 65 66 cnt++; 67 } 68}
試したこと
**の場所で例外が発生しているのかと思い、try,catchを入れたのですが、変わりませんでした。
補足情報
「#include "AnswerCheck.h"」は問題採点用のヘッダで、こちらにエラーが無い事は確認済みです。
また、読み込みファイルの「data.csv」は読み込むデータが1つのみ(Googleフォームの結果を落としているので2行)の場合は問題なく動きます。
追加
「data.csv」のサンプルです。
data.csv
開発環境はMinGW6.3.0です。
エディタはTeraPadを使用しています。
回答者のご指摘からmain関数にtry,catchを入れたところ、ひとまずエラーが解消されました。
ですが、入力したデータは4つ連続しているのですが、出力した「log.csv」には以下のように無駄に空白が入ってしまいました…
良ければ原因は何処なのか教えてほしいです…
回答3件
あなたの回答
tips
プレビュー