Avoid using global variables if possible - especially those that change. Your method wouldn't work anyway, because you try to set
x equal to
a before
a is set.
The code below will prompt the user for x and send it to your encrypting routine as an argument.
Other comments:
- If you mix cin >> and getline(), then note that cin >> will take its data, but won't necessarily pass the EOL character (\n), so the next getline() call will just take the rest of the "line", which will effectively be blank. I have circumvented this by another cin.ignore() call, but it is probably better to use getline() for any input and stringstream the resulting string into your variables (see the tutorials on this site).
- I think you could usefully learn about reading and writing files; see:
http://www.cplusplus.com/doc/tutorial/files/
For a standard text file, you basically have to:
- open a filestream with ofstream;
- write to it in exactly the same way as you would to the terminal, replacing 'cout' by the name of your stream;
- when you have finished, just close the filestream.
This is just three lines of code (in this program) and should be straightforward if you look at the tutorial.
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
|
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void Encrypt(string &letter, int x)
{
for (int i = 0; i < letter.length(); i++)
{
letter[i] += x;
}
}
int main()
{
int x;
string input;
cout << "please enter a number (you must give the person you send the message to the number)" << '\n';
cin >> x; cin.ignore(255, '\n');
cout << "Please enter text:" << '\n';
getline(cin, input);
Encrypt(input, x);
cout << input << '\n';
cin.get(); // effectively pauses
return 0;
}
|