opening file and putting into program

Please support our C++ advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Sep 2008
Posts: 12
Reputation: swbuko is an unknown quantity at this point 
Solved Threads: 0
swbuko swbuko is offline Offline
Newbie Poster

opening file and putting into program

 
0
  #1
Sep 17th, 2008
I'm writing a program that opens a file then sorts it a couple different ways then closes it. Someone in my class said something about using a getline function but I can't figure out how that works. I can't find a way to take a specific line in a text file and then put it into an array. How can I get each number into its own array?



4532 111 2123
324 3211 223
233 4493 992
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 15,679
Reputation: Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute 
Solved Threads: 1504
Team Colleague
Featured Poster
Ancient Dragon's Avatar
Ancient Dragon Ancient Dragon is offline Offline
Still Learning

Re: opening file and putting into program

 
0
  #2
Sep 17th, 2008
>>but I can't figure out how that works.
  1. #include <fstream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. ifstream in("filename.txt");
  8. string line;
  9. // read each line of the file
  10. while( getline( in, line) )
  11. {
  12. //blabla do something this line
  13. }
  14. }


>>I can't find a way to take a specific line in a text file
You have to read each line one at a time until you get to the line that you want.


>>How can I get each number into its own array?
What kind of array? int array?
  1. #include <fstream>
  2. #include <string>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. vector<int> arry; // array of integers
  9. ifstream in("filename.txt");
  10. int num;
  11. // read each line of the file
  12. while( line >> num )
  13. {
  14. arry.push_back(num); // add the number to the array
  15. }
  16. }
I told Santa what I wanted for Christmas and he washed my mouth out with soap.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the C++ Forum


Views: 371 | Replies: 1
Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC