+ 1

Why this code doesnt work: error

this code is supposed to take a sentence, then swap first and last letters of each word and add "ay'' at the end of each word #include <iostream> #include <string> #include <vector> #include <sstream> int main() { std::string input; int last, first = 0; char r; std::cin >> input; std::istringstream iss{input}; std::vector <std::string> words; std::string word; while (iss >> word) words.push_back(std::move(word)); std::string aword, result; for (int i = 0; i < words.size(); i++) { aword = words[i]; last = aword.front(); first = aword.back(); r = aword[last]; aword[last] = aword[first]; //swap aword[first] = r; aword = aword + "ay"; if (i == 0) result = aword + " "; if (i == words.size() - 1) result = result + aword; else result = result + aword + " "; } std::cout << result; }

2nd Oct 2020, 6:11 PM
ItzNekS
ItzNekS - avatar
2 Answers
+ 1
Not gone through entire code... A quick check on cin >> input.... Try to print value of input immediately after taking input post cin.... You will observe that it's not entire string stored in variable... For input string having space in between , plz use getline(cin,input)
2nd Oct 2020, 11:51 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
thanks for telling me about getline. i figured out the rest of the code, heres the result #include <iostream> #include <string> #include <vector> #include <sstream> int main() { std::string input; int last, first = 0; char r; std::getline(std::cin, input); std::istringstream iss{input}; std::vector <std::string> words; std::string word; while (iss >> word) words.push_back(word); std::string aword, result; for (int i = 0; i < words.size(); i++) { aword = words[i]; last = aword.length() - 1; first = 0; r = aword[last]; aword[last] = aword[first]; //swap aword[first] = r; aword = aword + "ay"; if (i == 0) result = aword + " "; else if (i == words.size() - 1) result = result + aword; else result = result + aword + " "; } std::cout << result; }
3rd Oct 2020, 9:03 AM
ItzNekS
ItzNekS - avatar