Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Having trouble merging cell data from a file. Characters are missing, so the final size is wrong, why?

I’m reading data from a file, merging 2nd and 3rd cells in each row, storing them in a new cell, then printing the data. Everything works fine except for two issues:

  1. The first '1' in the first cell in the first row gets truncated. Why does that happen?

  2. The value of size should have been 5, but it’s 6. Why?

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

#include<iostream>
using namespace std;
#define max 20
    
int main()
{
    string arr[max][5], temp;
    int i=0, j, k;
    char ch;
    freopen("input.txt", "r", stdin);

    while((ch = getchar()) != EOF)
    {
        for(j=0; j<5; j++)
        {
            if(j != 4)
                cin>>arr[i][j];
            else    
                arr[i][4] = arr[i][1]+arr[i][2];
        }
        i = i+1;

        //cout<<"\n";   
    }
    int size = i;
    cout<<"size: "<<size<<endl;

    for(i=0; i<size; i++)
    {
        cout<<arr[i][0]<<" "<<arr[i][1]<<" "<<arr[i][2]<<" "<<arr[i][3];
        cout<<"\n"; 
    }
    cout<<endl;

    return 0;
}   

Input file:

15101049 PRIYESH DAMOR p.damor
15101061 SIMRAN SONI simran.soni
15101012 KAUTAV BASUMATARY b.kaustav
15101053 RAHUL KUMAR rahul053
15101028 DUDDU VARA vara

Output:

size: 6 //size should have been 5
5101049 PRIYESH DAMOR p.damor //'1' before '5' is missing
15101061 SIMRAN SONI simran.soni
15101012 KAUTAV BASUMATARY b.kaustav
15101053 RAHUL KUMAR rahul053
15101028 DUDDU VARA vara

>Solution :

1. Because the first 1 is consumed by getchar() and you are not using ch.

2. Because the EOF check passes seeing the newline character at the end of 5th line and it proceeds to try to read the 6th line.

Instead of the while((ch = getchar()) != EOF) loop, try this:

    while(cin>>temp) // try to read first element, stop if it fails
    {
        arr[i][0] = temp; // assign what is read
        for(j=1; j<5; j++) // read the rest elements
        {
            if(j != 4)
                cin>>arr[i][j];
            else
                arr[i][4] = arr[i][1]+arr[i][2];
        }
        i = i+1;
        
        //cout<<"\n";
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading