Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using ifstream in c++

Tags:

c++

file

I have the following code to read in from a file

#include <queue>
#include <iostream>
#include <fstream>
#include <string>
main(int argc,char * argv[])
{
   ifstream myFile(argv[1]);
   queue<String> myQueue;
   if(myFile.is_open())
      {
         while(...
         ///my read here
      }
}

I have input file like this

1234 345
A 2 234
B 2 345
C 3 345

I want to do the equivalent of this in the read loop

myQueue.push("1234");
myQueue.push("345");
myQueue.push("A");
myQueue.push("2");
myQueue.push("234");
myQueue.push("B");
...

Whats the best way to do this?

Thanks!

like image 830
kralco626 Avatar asked May 27 '26 00:05

kralco626


2 Answers

string input;
myFile >> input;
myQueue.push(input);

Untested but I believe it works.

By the way, if you want to parse the whole file:

while(myFile>>input)

Thanks to rubenvb for reminding me

like image 175
F. P. Avatar answered May 28 '26 12:05

F. P.


#include <queue>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(int argc,char * argv[])
{
   if (argc < 2)
   {
      return -1;
   }

   ifstream myFile(argv[1]);

   queue<string> myQueue;
   string input;
   while(myFile >> input)
   {
         myQueue.push(input);
   }
}
like image 31
Sonny Saluja Avatar answered May 28 '26 14:05

Sonny Saluja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!