I'm having trouble with inputting lines. cin only gets me everything before the space. I've seen a few topics about this, and found getline(cin,var), and cin.ignore(), but nothing I've found works.
Here's my entire code (just in case something there was the real problem); the problem is in the main at the bottom:
/*
This program encodes and decodes a string,
using the substitutions given in the file code.dat
(however, the cin function will ignore space characters).
*/
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
class CodeGenerator {
char substitutions[96]; // array to be used as a reference when encoding and decoding
public:
CodeGenerator(string line) { // constructor
char temp; // holds an individual character; line is read char by char
for(int i = 0; i < line.length(); i++) {
temp = line[i];
substitutions[i] = temp; // reads in and stores the substitutions
}
}
string encode(string in) {
string out = string(); // output, empty string
int temp;
for(int i = 0; i < in.length(); i++) {
int temp = in[i]; //uses ASCII code of char as index for replacement in the replacement array
out += substitutions[temp - 32]; // encryption method is based on -32 system on the replacements
}
return out;
}
int search (char temp) { // finds index of given character
int index = 0;
while (substitutions[index] != temp) // loops until char is found
index++;
return index;
}
string decode(string in) {
string out = string(); // output string; initialized as empty
char temp;
for(int i = 0; i < in.length(); i++) {
temp = in[i];
out += (search(temp) + 32); // searches for index, and uses that to find ASCII value of original character
}
return out;
}
} ;
int main() {
string line, in, out;
ifstream file ("./code.dat");
if (file.is_open()) { // error handling
getline(file,line);
file.close();
}
else {
cout << "Could not open file\n";
return 0;
}
CodeGenerator codes = CodeGenerator(line);
cout << "Enter the message to be encoded.\n";
//cin >> in; this didn't work either
getline(cin, in);
out = codes.encode(in);
cout << "Here is the encoded message\n" << out << endl;
cout << "Here is the decoded message\n" << codes.decode(out) << endl;
return 0;
}
*code.dat just has 96 characters, ASCII 128-32, in a random order.
When I input anything with a space, it messes up, i.e.
"word1 word2 word3"
will be interpreted as
"word1"
The problem, I think is in
getline(cin,in)
I'm using g++ and mingw compilers.
Help?
^that code worked, but mine... doesn't, even though they're basically identical. Does it have anything to do with my getting input from a file before getting that line?
It worked!
Not sure what did the trick, but it works now.
Just to be clear,
cin >> in;
will still only read what comes before the space, while
getline(cin, in);
will read all of it?