0

I have read a csv file in string format using getline() function, then to store the marks column value in an integer type array I used stringstream. Then using a for loop I stored the first 10 marks in an array.

But when I am printing the values of the array outside of the loop from which we are reading the values of the CSV file it prints 0 for all marks and not retaining the values.

I tried making the array global and tried shifting the loop in which we are storing the marks in the array outside the loop in which we are reading the CSV file values but when i did this only the last value is getting print.

So, I want the values to get preserved outside the loop of reading CSV file such that we can use the array through out the program. enter image description here

int main()
{
    sorting obj;
    int arr1[10];
    ifstream o1("student.csv");
    if(!o1.is_open()) cout<<"error";
    string serialno;
    string name;
    string marks;
    string age;
    int du;

    for(int i=0; i<10; i++)
    {
        getline(o1, serialno,',');
        getline(o1, name,',');
        getline(o1, marks,',');
        getline(o1, age, '\n');
        //cout<<"student name :"<<name<<"\n";

        stringstream geek(marks);
        int marks1;
        geek >> marks1;

        for(int j = 0; j < 1; j++)
        {
            arr[j] = marks1;
            du = marks1;
        }

        for(int j = 0; j < 1; j++)
        {
            cout<<"test";
            cout<<arr[j]<<" - ";
        }
    }

    for(int c=0; c<10; c++)
    {
        cout<<arr[c]<<" ";
    }
Danny_ds
  • 11,201
  • 1
  • 24
  • 46
  • 1
    When you say you stored "all the marks" just how many marks do you think `for(int j = 0; j < 1; j++)` is going to store, and since you're overwriting `arr[0]` with each iteration, that's all you're ever going to get. that one, and in this case, the last one of that one. – WhozCraig Apr 20 '20 at 11:42
  • Does this answer your question? https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c – 463035818_is_not_an_ai Apr 20 '20 at 11:44

0 Answers0