Syed Ali Tehsin Syed Ali Tehsin - 2 months ago 10
C++ Question

C++ programming I/O

I am trying to take input from a text file containing 1000 records.


  • 10

  • 1 100

  • 2 101

  • 3 123

  • 4 124

  • .

  • .

  • .

  • 1000 1234



I am using the code below to take the input in three variables d=10 (first line of the text file, a contains all the numbers in first column and b contains all the numbers in second column.

The problem I am facing with this code is it takes the last half of the file as input the first half is ignored.

output:


  • 500 3211

  • 501 3212

  • 502 22121

  • .

  • .

  • .

  • 1000 1234

    char fileName[20];
    cout << "Enter input test file name: ";
    cin >> fileName;

    ifstream readFile; //object of input file stream
    readFile.open(fileName); //open a file

    //Check for an error
    if (readFile.fail())
    {
    cerr << "Error Opening File" << endl;
    }
    string c, d,a,b;
    getline(readFile, c);

    for (int i=0; i<1000;i++)
    {
    getline(readFile, readLine);
    istringstream split(readLine);
    getline(split, a);
    getline(split, b);
    cout <<serverNum<<" "<<a<<" "<<b<<endl;
    }



can someone suggest me why am I facing this

Answer

A better way would be this:

#include <iostream> // std::cout, std::endl
#include <fstream>  // std::ifstream
using namespace std;

int main()
{
    // open your file
    ifstream input_file("test.txt");

    // create variables for your numbers
    int first_num, left_num, right_num;

    // determine the first number in your file
    input_file >> first_num;

    // while there is a number on the left, put that number into left_num
    while(input_file >> left_num)
    {
        // put the corresponding right number into right_num
        input_file >> right_num;

        // now you can work with them
        cout << left_num << ' ' << right_num << endl;
    }

   // close the file
   input_file.close();

   return 0;
}

Edit:

@Syed the problem could be that your command line doesn't have enough buffering and just overwrites your previous 500 lines. Just go to your cmd, click the top left corner, go to settings, layout, and increase the buffer. The code works, it must be your console.

Also since you answered with a list containing floats, you might want to consider changing left_num and right_num from int to float or double.

Comments