Reading Numbers from files...

This is a discussion on Reading Numbers from files... within the C++ Programming forums, part of the General Programming Boards category; Hi Guys! Just wondering, is it possible to read a number from a txt file? If so how? I have ...

  1. #1
    Registered User
    Join Date
    Nov 2004
    Location
    Pennsylvania
    Posts
    434

    Reading Numbers from files...

    Hi Guys! Just wondering, is it possible to read a number from a txt file? If so how? I have been trying for a while and cant seem to figure it out. Any help would be greatly appreciated.

  2. #2
    Registered User Sake's Avatar
    Join Date
    Jan 2005
    Posts
    89
    >is it possible to read a number from a txt file?
    Yes, and C++ makes it very easy. Once you open a file stream, you can use it just like cin:
    Code:
    #include <cstdlib>
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      int number;
      ifstream fin("file.txt");
    
      // Always check for failure
      if (!fin) {
        cerr<<"Error opening file\n";
        return EXIT_FAILURE;
      }
    
      // Likewise, any input should be checked
      if (!(fin>> number)) {
        cerr<<"Input error\n";
        return EXIT_FAILURE;
      }
    
      cout<<"The number read was "<< number <<endl;
    
      return EXIT_SUCCESS;
    }

  3. #3
    Self-Taught Noob
    Join Date
    Jan 2005
    Location
    Ohio
    Posts
    38
    ive been trying to do the same thing but that only would work for the first number in the file it wouldnt work if you hadsay 50 numbers in the file.

    how would you do that?
    No one died when Clinton lied.

    Compiler: Borland C++ Builder
    OS: Windows XP

  4. #4
    Lead Moderator kermi3's Avatar
    Join Date
    Aug 1998
    Posts
    2,595
    Kermi3

    If you're new to the boards, welcome and reading this will help you get started.
    Information on code tags may be found here

    - Sandlot is the highest form of sport.

  5. #5
    Self-Taught Noob
    Join Date
    Jan 2005
    Location
    Ohio
    Posts
    38
    ive read the tutorial and i still didnt se how you would choose one number outta 50 in one already created text file
    No one died when Clinton lied.

    Compiler: Borland C++ Builder
    OS: Windows XP

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Hm... how about a loop?

    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    I think what your looking for is something like this:

    Code:
    #include <cstdlib>
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int main(){
    
        int x = 0;
        int number[10];
        ifstream myFile;
    
        myFile.open("File.txt"); //open file
    
        if(!(myFile.is_open())) { //ensure file opened
            cout <<"Error opening file";
            return 0;
        }
    
        while(!(myFile >> number[x] == NULL) && (x < 10)) { //check for EOF and ensure do not overrun array
            x++;
        }
    
        for(int i =0; i < 10; i++) {
            cout << number[i] << endl; //print result
        }
        return 0;
    }
    *edit*
    Now if you do not know how much you are inputting you could eihter dynamically reallocate the array or just use the vector class(easiest approach).
    *end edit*

    Happy Coding!!
    Last edited by andyhunter; 01-24-2005 at 02:29 PM.
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

  8. #8

  9. #9
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    Oops! My bad, thanks for pointing that out. I updated my code so it doesn't show that bad, terrible bug causing thing anymore.

    -Andy
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

  10. #10
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,801
    Just made a few improvements on yours andy.
    Code:
    #include <iostream>
    #include <fstream>
    
    int main(void)
    {
      
      int i = 0, j;
      int number[10];  
      std::ifstream myFile;
      myFile.open("file.txt");
      
      if(!myFile)//file doesn't exist or some other reason for it failing
      {
        
        std::cout<<"Could Not Open file.txt"<<std::endl;
        std::cin.get();
        return 0;
        
      }
      
      while(myFile>>number[i] && i < 10)//input numbers in our file only up to 10 numbers
      {
        
        i++;
        
      }
      
      for(j = 0; j < i; j++)//only printing the numbers that we read in
      {
        
        std::cout<<number[j]<<std::endl;
        
      }
      std::cin.get();    
      return 0;  
      
    }
    Last edited by prog-bman; 01-24-2005 at 08:56 PM.
    Woop?

  11. #11
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    nice, I see you are a fan of the C99 standard too:
    int main(void)
    [edit]
    How about this -

    Code:
    #include <iostream>
    #include <fstream>
    #include <stdlib.h>
    
    int main(void){
    
    	int x=0, arraySize=0;
    	int* number = NULL;
    	std::ifstream myFile;
    
    	myFile.open("File.txt"); //open file
    
    	if(!myFile) { //ensure file opened
    		std::cout <<"Error opening file";
    		std::cin.get();
    		return 0;
    	}
    
    	while(!((myFile >> x)==NULL)) { //check for EOF
    		if(!(number = (int*)realloc(number, (arraySize+1) * sizeof(int)))){  //resize array by one int
    			std::cout << "Error allocating array" << std::endl;
    			std::cin.get();
    			return 1;
    		}
    		number[arraySize++] = x;
    	}
    
    	for(int i =0; i < arraySize; i++) {
    		std::cout << number[i] << std::endl; //print result
    	}
    	std::cin.get();
    	return 0;
    }
    Now of course in reality you would resize in chunks, but this is just an example.

    -Andy

    [/edit]
    Last edited by andyhunter; 01-24-2005 at 08:15 PM.
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

  12. #12
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,801
    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    
    int main(void)
    {
      
      int x = 0, arraySize = 0, i = 0;
      std::vector<int> number;  
      std::ifstream myFile;
      myFile.open("file.txt",std::ios::in);
      
      if(!myFile)//file doesn't exist or some other reason for it failing
      {
        
        std::cout<<"Could Not Open file.txt"<<std::endl;
        std::cin.get();
        return 0;
        
      }
      
      while(myFile>>x)//input numbers in our file only up to 10 numbers
      {
        
       
        number.push_back(x);
        arraySize++;    
           
        
      }
      
      for(i = 0; i < arraySize; i++)//only printing the numbers that we read in
      {
        
        std::cout<<number[i]<<std::endl;
        
      }
      std::cin.get();    
      return 0;  
      
    }
    Last edited by prog-bman; 01-24-2005 at 08:42 PM.
    Woop?

  13. #13
    Self-Taught Noob
    Join Date
    Jan 2005
    Location
    Ohio
    Posts
    38
    i dont think you guys understand what im saying. I am using this to save and load characters in a text (console) adventure. I create the table to a txt file and i can get it to display but i cant get the loaded characters stats to apply to the ones in the txt file.

    you guys are showing me how to show all of them in the 50 numbers or characters i need to move the curser to a specific position and load from there.
    No one died when Clinton lied.

    Compiler: Borland C++ Builder
    OS: Windows XP

  14. #14
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    If you are dealing with the file while your program is running the best thing to do is to load the file into a memory structure such as a vector and manipulate it from there. Once your program is completely done with the information save the vector back into the file. The following is an example of loading a file into a vector and then only displaying the 3rd through the 5th numbers.

    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    
    int loadFile(std::vector<int>*, const char*);
    
    int main(void) {
    
        std::vector<int> vFile; //create vector to hold file information
        std::vector<int>::iterator iFile; // create iterator to move through vector
        int offset = 0;
    
        if((loadFile(&vFile, "FileDemo.txt")) == 1) { //load our file into the vector and check for an error
            std::cout << "Error Loading File" << std::endl;
            std::cin.get();
            return 1;
        }
    
    
        std::cout << "Printing from the file starting a the 3rd number and going to the 5 number" << std::endl;
        
        offset = 2;
        for(iFile = (vFile.begin() + offset); iFile < (vFile.begin() + 5); iFile++) { //move through the vector
            std::cout << *iFile << std::endl;
        }
        
        std::cin.get();
        return 0;
    }
    int loadFile(std::vector<int>* my_vector, const char * szfileName) {
    
        std::ifstream myFile;
        int myNumber = 0;
    
        myFile.open(szfileName, std::ios::in);//Load the file
    
        if(myFile == NULL) //check for error
            return 1;
    
        while(!((myFile >> myNumber)==NULL)) { //check for EOF
            my_vector->push_back(myNumber); // load contents of file into vector
        }
    
        myFile.close();
        return 0;
    }
    Happy Coding!!
    Last edited by andyhunter; 01-26-2005 at 04:24 AM.
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Holy Deja-Vu, Batman!

    Let's spell this out very slowly: If some one makes a post such as the origional posters, and then hasn't checked back in over 10 posts, they probably don't really want to learn anything. They want the whole thing done for them. And guess what? There are a bunch of suckers posting here who're just jumping at the chance to do it. Thank you for contributing to the never-ending flow of this type of post.

    Quzah.
    Hope is the first step on the road to disappointment.

Page 1 of 3 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question: reading numbers into an array
    By Lince in forum C Programming
    Replies: 15
    Last Post: 11-15-2006, 02:41 AM
  2. pulling numbers from files....
    By Confuzz in forum C++ Programming
    Replies: 3
    Last Post: 09-07-2004, 07:49 PM
  3. Reading selective numbers from a file
    By supaben34 in forum C++ Programming
    Replies: 4
    Last Post: 11-21-2002, 12:56 PM
  4. problem reading files in C
    By angelfly in forum C Programming
    Replies: 9
    Last Post: 10-10-2001, 11:58 AM
  5. Need Advice in reading files
    By jon in forum C Programming
    Replies: 4
    Last Post: 10-07-2001, 07:27 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21