#include <string>
int main(){
std::string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
std::string key {"XZNLWEBGJHQDYVTKFUOMPCIASRxznlwebgjhqdyvtkfuompciasr"};
// in this version of the cypher, we'll use more string functions
std::string secret_message{};
size_t char_position{};
std::cout << "Enter a secret message:\n";
getline(std::cin, secret_message); // getline function gets the whole input including spaces
for(size_t i = 0; i < secret_message.length(); ++i){
char_position = alphabet.find(secret_message[i]);
secret_message[i].swap(key[char_position]);
}
Return 0;
} ```
#syntax wrong
15 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
The last line in the for loop shows an error on secret_message[i]
It says expression must have class type
But secret message is a stdstring how is it not class type
- You're doing Return 0; instead of return 0;
- Didn't include <algorithm> header to use the swap function
try this instead
std::swap(secret_message[i], key[char_position]);
#include <string>
int main(){
std::string name = "Manuel";
std::string name2 = "Bill";
name2.swap(name);
std::cout << name; // will output Bill
return 0;
}```
I had a prior program that worked fine see
oh nvm the last thing I mentioned then
But it worked when I changed it to std::swap(secret_message[i], key[char_position]);
so I'm not sure what's going on
;compile ```c++
#include <iostream>
#include <string>
int main(){
char a = 'a';
char b = 'b';
int c = 1;
int d = 2;
a.swap(b);
c.swap(d);
std::cout << a;
std::cout << c;
return 0;
}
Compiler Output
<source>: In function 'int main()':
<source>:10:7: error: request for member 'swap' in 'a', which is of non-class type 'char'
10 | a.swap(b);
| ^~~~
<source>:11:7: error: request for member 'swap' in 'c', which is of non-class type 'int'
11 | c.swap(d);
| ^~~~
Build failed
nou2917 | c++ | x86-64 gcc 14.2 | godbolt.org
I guess the .swap() doesn't work with primitive types
Yeah, because primitive types aren't classes that could have member functions
Makes sense