Using ifstream in C ++

I have the following code to read 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 an input file like this

1234 345
A 2 234
B 2 345
C 3 345

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

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

What is the best way to do this?

Thank!

+3
source share
2 answers
string input;
myFile >> input;
myQueue.push(input);

Unconfirmed, but I believe that it works.

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

while(myFile>>input)

Thanks rubenvb for reminding me

+6
source
#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);
   }
}
+2
source

Source: https://habr.com/ru/post/1779786/


All Articles