How do i insert a string from a txt file into function?

if i have an int main where i ask the user for a txt file then ask them to insert a string into it, how can i grab the string from that file and insert it into a function? Within the function parameters i cannot have the string itself, i can only have the filename, so how do i go about opening that file and using its string within the function?

for ex: (a code to encrypt/decrypt a Caesar Cypher)

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

std::string encrypt(std::string filename, int key);  
void decrypt(std::string encrypted, int key); 

string encrypt(std::string filename, int key)
{
	string text;
	int dist = text.length();
	
	for (int i = 0; i < dist ; i++)
    {
		if ((text[i] >= 'A') && (text[i]<= 'Z'))
        {
			text[i] = text[i] + key;
			cout<<text[i];
        }
        else if ((text [i] >= 'a')&&(text[i] <= 'z'))    
        {
			text[i] = text[i] + key;
			cout<<text[i];
        }
	}
	return text;
}

void decrypt(std::string encrypted, int key)
{
	
	return ;
}
 
int main ()
{
	int key = 1 ;
	string filename = "hw.txt";
	string text;

	
	ofstream myfile;
	myfile.open(filename.c_str());
	
	cout<<"Insert text: ";
	getline(cin,text);
	
	encrypt(filename, key);
	
	
	myfile<<text;
	
	myfile.close();

	
	return 0;
}
Last edited on
If I understand your question correctly, you are simply trying to read a string from a file... Start reading this tutorial [ http://www.cplusplus.com/doc/tutorial/files/ ] and you should be able to do it easily.
Last edited on
Topic archived. No new replies allowed.