Question about Reading text files into strings from command line

Hi guys,

I am currently trying to write a program which involves me writing two arguments to the command line like so:


> program 1.txt 2.txt

>1.txt

>2.txt



After that, the contents of each file should be stored into a string.
My question is I'm confused how to use ifstream to do that.


Here is my code right now -> I just print out the arguments entered into the command line to verify it works and they do... I just don't know how to store them into strings.



Thank you in advance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 #include <iostream>
#include<string>
#include<fstream>
#include<sstream>
 
 
using namespace std;
 
int main(int argv, char ** argc) 
{
	if (argv >= 3) 
	{
 
		cout << argc[1] << endl;
		cout << argc[2] << endl;
 
		ifstream file(argc[1]);
		string s;
 
		while (getline(file, s))
		{
			cout << s << endl;
		}
	}
 
}
//cl /EHsc hw4.cpp s1.txt t1.txt 
You are almost there:

1
2
3
4
5
6
7
string s;
string full = "";
while (getline(file, s))
{
	cout << s << endl;
        full += s; // String concatenation;
}


EDIT: Not totally sure if you want to save the lines into strings or the files into strings:

1
2
3
4
string s;
std::vector<std::string> filestring_vector;
while(std::getline(file,s)
    filestring_vector.push_back(s);
Last edited on
Topic archived. No new replies allowed.