I have the trans function which uses a single parameter, has to be void, and returns through c the opposite case of a letter from a word input in main.
Example: input: dOgdoG output: DoGDOg The function does change the case, but i cant figure out a way to build the new word / replace the old one because i keep getting compiling errors regarding "const char" or "invalid conversions".
The following program gives error "invalid conversion from char to const char*
I only changed the type of the function for example purposes.
#include <iostream> #include <cstring> #include <fstream> using namespace std; char trans(char c) { if(c >= 'a' && c <= 'z') return c-32; else if(c >= 'A' && c <= 'Z') return c+32; } int main() { char s[101], s2[101] = ""; cin >> s; int i; for(i=0; i<strlen(s); i++) { strncat(s2, trans(s[i]), 1); } cout<<s2; return 0; } EDIT: I changed from the char function to a void function and removed the body of the for.
void trans(char c) { if(c >= 'a' && c <= 'z') c-=32; else if(c >= 'A' && c <= 'Z') c+=32; } int main() { char s[101], s2[101] = ""; cin >> s; int i; for(i=0; i<strlen(s); i++) { /// i dont know what to put here } cout<<s2; return 0; }
toupperandtolowerfunctions.strncat; you know thats2is large enough to hold the result, because you wrote it that way. So just do it:s2[i] = trans(s[i]);. And don't forget the nul terminator; that comes after the last character, so looping up tostrlen(s)won't reach it.sdirectly.i<strlen(s)in theforloop probably means that your loop hasO(N*N)time complexity, whereNis the length ofs, sincestrlen(s)itself hasO(N)complexity, and theforloop itself runsNtimes. I'd recommend having the statementint len = strlen(s);before the loop, and then havei<leninstead ofi<strlen(s). (Take a look at joelonsoftware.com/2001/12/11/back-to-basics/.)