[英]Atoi function while reading a .csv file C++
到達“ atoi”功能時,我的代碼執行崩潰,但我不明白為什么。 該代碼應該從.csv文件中讀取矩陣,考慮如下:-第一行(直到第一個'\\ n'),並將每個元素(以','分隔)保存為ints向量; -矩陣的其余部分,通過查看每個元素並在讀取的數字為1或2的情況下創建特定的對象。在調試程序時我沒有遇到任何異常,它只是在執行過程中崩潰(並使用系統( “ PAUSE”)我可以弄清楚這是atoi函數無法正常運行)。 您能幫我了解問題出在哪里嗎? 非常感謝你。 附:我還附上了我正在加載的所有庫...也許可以幫上忙:)
#include <fstream>
#include <stdio.h>
#include <sstream>
#define nullptr 0
#include <string>
#include "classi.h"
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
ifstream file("problem.csv");
unsigned int N = 0;
unsigned int M = 0;
char c; //modificato char * c;
unsigned int i=0,j=0, k=0, n_iter, j_temp =0;
std::vector<car> v_row;
std::vector<car> v_col_temp;
std::vector<int> iter; // location where I want to save the ints corresponding to the elements of the first row of the .csv file //
std::string iterazioni; //location where I want to save the first row as a string and then cut it into pieces (iteraz) and then convert (atoi --> iter)
std::string iteraz;
while(!file.eof()){
std::getline(file,iterazioni,'\n');
stringstream it(iterazioni);
while (it.good()) {
std::getline(it,iteraz, ',');
iter[k] = atoi(iteraz.c_str());
if(iter[k]<0){
cout<<"Errore: negative #of iterations"<<endl;
break;
}
iter.push_back(0);
k++;
}
iter.pop_back();
file.get(c);
if (c=='1'){
blue_car b(i,j);
if (v_col_temp[i].get_next() != nullptr)
v_col_temp[i].insert_tail(&b);
else
v_col_temp[i].insert_head(&b);
}
if (c=='2'){
red_car r(i,j);
if (v_row[i].get_next() != nullptr)
v_row[i].insert_tail(&r);
else
v_row[i].insert_head(&r);
}
if (c==',') {
j++;
if (i == 0)
j_temp++;
}
if (c=='\n'){
car p;
v_row.push_back(p);
v_col_temp.push_back(p);
i++;
if (j != j_temp) {
std ::cout<<"errore input non valido: numero righe/colonne non coerente"<<endl;
}
j=0;
}
else if ((c!='\n') && (c!=',') && (c!='0') && (c!='1') && (c!='2'))
std ::cout<<"errore input non valido"<<endl;
};
n_iter = k-1;
M=i;
N=j+1;
...
您的程序崩潰是因為您未能初始化iter
向量的內容。
std::vector<int> iter; // location where I want to save the ints corresponding to the elements of the first row of the .csv file //
您聲明並構造此向量。 該向量此時為空,並且沒有任何元素。
稍后在某個時候:
iter[k] = atoi(iteraz.c_str());
k
的初始值為0,因此這會嘗試將atoi()
的返回值分配給iter[0]
。
當然,問題是沒有iter[0]
。 此時, iter
向量仍然為空。
附加評論,至少對於stackoverflow.com上至少50%的此類問題是正確的:
1)“使用命名空間std”; 這是一個壞習慣,應該避免
2)也不要使用您在問題中引用的system(“ pause”) 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.