Reading in text file in c++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SUNIL TYATA
    New Member
    • Feb 2010
    • 18

    Reading in text file in c++

    I've 13 int number as a list in txt file.
    34
    55
    99
    120
    57
    45
    49
    30
    32
    21
    56
    22
    0


    The last value is a 0 and is NOT one of the values to be used in any calculation . I am supposed to create only one array as global variable.
    So what would be the logic behind(with code) to read all the numbers from the file except the last one (i.e, 0) and put them in globally created array.

    and if 0 is situated between 45 and 49; in that case we have to take that 0 as the value of array.

    Thank you !
    I hope I'll get solution soon...
  • manontheedge
    New Member
    • Oct 2006
    • 175

    #2
    first, look up "fstream" to find out how to read a text file and store the data ( there are other ways, but fstream is one of them )

    then, learn about arrays so you see how you can put values in it ( the values from the text file )

    try to get the file reading and array storing to work and people will be much more likely to help you out. If you have problems with either of those, after you've read about it and tried it, post your code and let us know what specifically you're having trouble with.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      If you know there are ints in the file and you need only 12, you might try:

      myfile >> arr[0] >> arr[1] etc...

      or use a loop where myfile is an ifstream.

      Comment

      • SUNIL TYATA
        New Member
        • Feb 2010
        • 18

        #4
        If I dont know how many number are there in the file. It might more than 12 might be 14 or 16 or 17 whatever (within 20). Here I've to pick up the numbers up to second last from a file.
        like I already create global array as

        #include<iostre am>
        #include<fstrea m>
        using namespace std;
        int main()
        {
        const int size = 20;
        int arr[20];
        int count=0;
        fstream infile;
        infile.open("c:/C++/array1.txt");
        if(!infile)
        {
        cout<<"Error! Can't open the file.";
        }

        do
        {
        infile>>arr[count]; //so here what code will help me to read up to second last integer value from the file.
        count++;
        }while(!infile. eof());

        cout<<endl<<"Si ze of the array is:"<<count;

        for(int i=0;i<count;i++ )
        {
        cout<<endl<<"ar r["<<i<<"] = "<<arr[i];
        }

        cout<<endl;
        infile.close();
        return 0;
        }

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          You may need to seek to the end of the file and then back up two integers and then read the file backwards to the begininng.

          Code:
          ifstream myfile;
          myfile.seekg(SEEK_END - 2*sizeof(int));
          The beginning of the file is SEEK_SET.

          This assumes no whitespeace between the ints.

          Comment

          • SUNIL TYATA
            New Member
            • Feb 2010
            • 18

            #6
            wher I can use the code you send me

            your code is below

            ifstream myfile;
            myfile.seekg(SE EK_END - 2*sizeof(int));

            in my code bellow

            #include<iostre am>
            #include<fstrea m>
            using namespace std;
            int main()
            {
            const int size = 20;
            int arr[20];
            int count=0;
            fstream infile;
            infile.open("c:/C++/array1.txt");
            if(!infile)
            {
            cout<<"Error! Can't open the file.";
            }

            do
            {
            infile>>arr[count]; //so here what code will help me to read up to second last integer value from the file.
            count++;
            }while(!infile. eof());

            cout<<endl<<"Si ze of the array is:"<<count;

            for(int i=0;i<count;i++ )
            {
            cout<<endl<<"ar r["<<i<<"] = "<<arr[i];
            }

            cout<<endl;
            infile.close();
            return 0;
            }

            Comment

            • weaknessforcats
              Recognized Expert Expert
              • Mar 2007
              • 9214

              #7
              do
              {
              infile>>arr[count]; //so here what code will help me to read up to second last integer value from the file.
              count++;
              }while(!infile. eof());
              This will read all of the integers in the file. But: a) your arr must be large enough to hold all the ints (currently it's too small) and b) the count will be incremented before the end of file is tested. Therefore, decrement count when you leave the loop.

              So, if you read 10 ints then you can work with the first 8 so satisfy the "up the second from the end" requirement.

              With reading, you cannot read the file correctly unless you already know the format. So unless you know ahead of time how mnay ints there are, you have no choice but to read them all in order to find out which are the last two.

              Comment

              • SUNIL TYATA
                New Member
                • Feb 2010
                • 18

                #8
                Its ok counter part I will handle it. but isn't there any function in fstream
                library that will help me to loop through the text file till second last of the number list.
                The actual question is like this
                Q. Write a program that will manipulate an array. Your program should handle up to 20 integer numbers. Declare the array as a global variable. (This is the only time you should use a global variable.)



                For each print out produced below, label the results. Also print your output in the order listed below.



                Write a function for each part. You should have a single program with multiple functions.

                _______________ ______________



                1. Read the integer values into the array from a file. The last value is a 0 and is NOT one of the values to be used in any calculation below. A sample input file is provided with the assignment.


                2. Print out all the values in the array with no more than 5 numbers per output line.



                3. Print out the average of the numbers.



                4. Print out how many numbers are larger than the average and how many are smaller than the average. Pass average as a parameter to the function..



                5. For every odd location in the array, subtract it from the previous even location and store results in the even location. Print out all values in the array (a previous requirement)



                6. Print out the average for the new array.



                7. Convert every negative numbers to positive numbers. Print out the array.



                8. Swap the first number in the array with the last number in the array. Print out the array.



                9. Print out the average for the new array.




                input file:




                34
                55
                99
                120
                57
                45
                49
                30
                32
                21
                56
                22
                0

                Comment

                • jkmyoung
                  Recognized Expert Top Contributor
                  • Mar 2006
                  • 2057

                  #9
                  With something tricky like the average, you'll have to keep track of all your inputs, because one number at the end could throw the average off.

                  To make input simpler, make your array of size 21 so that 0 can fit in the 21st spot (index 20) if needed. After you read in the final 0, just decrement the counter by 2 to let you know your maximum index, (1 for the 0, and 1 because of the extra count++ at the end), before processing your numbers.

                  Comment

                  • SUNIL TYATA
                    New Member
                    • Feb 2010
                    • 18

                    #10
                    But It has already been said in the question that Your program should handle up to 20 integer numbers. Declare the array as a global variable..
                    In the real code I am not supposed to make the array of size 21. Thank you!

                    Comment

                    • jkmyoung
                      Recognized Expert Top Contributor
                      • Mar 2006
                      • 2057

                      #11
                      Why not? If you make the array of size 21, it handles up to 20 integers. If you make the array of size 20, it only handles up to 19 integers. Doesn't logic follow that you should make the array of size 21? Challenge your own assumptions man.

                      Either that or add a pesky if clause inside the loop.

                      Comment

                      • SUNIL TYATA
                        New Member
                        • Feb 2010
                        • 18

                        #12
                        I did it! Thanks for encouragement see u with next Quest...

                        Comment

                        • weaknessforcats
                          Recognized Expert Expert
                          • Mar 2007
                          • 9214

                          #13
                          Originally posted by jkmyoung
                          If you make the array of size 21, it handles up to 20 integers.
                          Maybe I am missing something but an array of size 21 will handle 21 integers.
                          They will be identified as elements 0 to 20.

                          Therefore, and array of 20 is all that's required here.

                          Comment

                          • jkmyoung
                            Recognized Expert Top Contributor
                            • Mar 2006
                            • 2057

                            #14
                            If you have an array of 20, you have to constantly check after each element:
                            "Am I done?"
                            And EVEN then you need to still read in the last 0 element.
                            An array of 21 holds 20 values plus a "Sentinel" value of 0.

                            Benefits of array[20]:
                            non-element data is never read into data array.
                            May be easier to understand.
                            1 less array space needed.
                            You never read 0 into your calculations.
                            Handles error input better

                            Detriments:
                            Slower, requiring extra check every iteration.
                            Requires extra boolean space
                            Less elegant code.
                            If you think of 0 as a "sentinel" ending value then there is no disconnect.
                            Must detriment the counter anyways after use.

                            To be honest, I was just trying to give the original poster the quickest way to solve their problem without a lot of explanation and code changes.

                            Comment

                            • weaknessforcats
                              Recognized Expert Expert
                              • Mar 2007
                              • 9214

                              #15
                              Ah, I see.

                              However, a sentinel value of 0 is still a valid integer value. The entire array could be filled with 0's.

                              In this case a counter for the number of elements that are active in the array may be safer. Especially if there are multiple 0 values.

                              Comment

                              Working...