weird problem... (C++) | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 2

weird problem... (C++)

i am making a Caesar cipher encoder. heres the code: ////////////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <string> #include <map> using namespace std; int main(){ map <string,int> charmap = {{"a",0},{"b",1},{"c",2},{"d",3},{"e",4},{"f",5},{"g",6},{"h",7},{"i",8},{"j",9},{"k",10},{"l",11},{"m",12},{"n",13},{"o",14},{"p",15},{"q",16},{"r",17},{"s",18},{"t",19},{"u",20},{"v",21},{"w",22},{"x",23},{"y",24},{"z",25}}; int rot; string text; string chars[27] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",}; cout << "enter a value (1 to 23): "; cin >> rot; cout << "\n" << "enter some text to encode: "; cin >> text; std::cin.ignore(); cout << "\noutput: "; int size = text.length(); /* debug start*/ cout << "size:" << size <<endl; cout << "text:" << text <<endl; /* debug end*/ for (int loop = 0; loop < size; loop++){ string tempchar = text.substr(loop); if (tempchar == "!") { cout << " "; }else { int temploc = charmap[tempchar]; temploc += rot; if(temploc>25){ temploc -= 26; } cout << chars[temploc]; } }; return 0; } ////////////////////////////////////////////////////////////////////////////////////// when i use it... this happens input: 1 hello output: bbbbp whats going on? also c++ only accepts input before white space when using "cin" for example if i inputted "hello there" it would only get the "hello" part. is there a way i can bypass it?

22nd Jul 2017, 10:03 AM
Seth Thompson
Seth Thompson - avatar
3 Respuestas
+ 7
see getline() to get whole lines of text. http://www.cplusplus.com/reference/string/string/getline/
22nd Jul 2017, 10:09 AM
jay
jay - avatar
+ 7
Hey there nice code! I haven't actually run it so I'm just guessing, but i think you forgot to give a second, "length" argument to substr(): string tempchar = text.substr(loop); gives the values "hello", "ello", "llo", "lo", and "o", of which only the last one is in the Map, and then when you do the lookups: int temploc = charmap[tempchar]; you get (because of the way Map::operator[] seems to work): temploc: 0, 0, 0, 0, 14 and after adding rot: temploc: 1, 1, 1, 1, 15 which explains the "b"s (and the "p") in cout << chars[temploc];.. ..so maybe try: string tempchar = text.substr(loop, 1); ? Hope this helps! @jay Great link to a really useful site (I looked up Map and string::substr there). Thanks!
23rd Jul 2017, 8:14 AM
Karbz P
Karbz P - avatar
+ 2
There is no need of map here. char type is converted to int "under the hood". For example: char smh = 'a'; smh++; std::cout << smh; // output: b
22nd Jul 2017, 12:01 PM
Jakub Stasiak
Jakub Stasiak - avatar