如何在没有库函数的情况下反转字符串 - C ++

时间:2017-04-23 19:15:12

标签: c++ string char

我无法理解如何输出字符串的反转,然后存储反转值并将其应用于字符串变量以便稍后打印字符串。我收到的一些错误取决于程序的结构包括:打印随机字符,只打印字符串输入,编程崩溃......程序必须能够处理此菜单:

enter image description here

有一次,我有反向工作,但是当我添加例如if(choice ==' 2')并创建反向函数时,它将再次开始动作。

这就是我现在所拥有的:

int main()
{
    string userString = "";
    int i = 0;
    char choice;
    char invChar = char(userString[i]);
    userString = invChar;



    cout << "Please enter a word, a sentence, or a string of numbers." << endl;
    getline(cin, userString);

    do
    {

        cout << "\nUSE THIS MENU TO MAINPULATE YOUR STRING\n"
             << "----------------------------------------" << endl;
        cout << "1) Inverse String\n" 
             << "2) Reverse String\n" 
             << "3) To Uppercase\n"
             << "4) Count Number Words\n" 
             << "5) Count Consonants\n" 
             << "6) Enter a Different String\n"
             << "7) Print the String\n" 
             << "Q) Quit" << endl;

        cin >> choice;
        cin.ignore();

        if (choice == '1')
        {
            for (int i = 0; i <= userString.length(); ++i)
            {
                if (isupper(userString[i]))
                {
                    char(tolower(userString[i])); // if uppercase - converts to lower - if upper keeps value
                    invChar += userString[i];

                }

                userString = invChar;

            }       

            cout << userString;


        }

    } while (choice != 'q' || choice != 'Q');

提前感谢任何提示和技巧!

1 个答案:

答案 0 :(得分:0)

您是否有意这样做:

for (int i = 0; i < userString.length(); ++i)
{
   if (isupper(userString[i]))
   {
       userString[i] = (tolower(userString[i]));
   }
   else if(islower(userString[i]))
   {
       userString[i] = (toupper(userString[i]));
   }
}

这实际上是相反的。你之前做的事情不起作用,也只能转换为大写