我的工作是写一个程序,将句子转换为大写和小写。

#include <iostream>
using namespace std;


int main ()
{
int current;
string sent;
cout << "Please enter a sentence: ";
cin >> sent;
for (int i = 0; i < sent.length(); i++)
{
    current = (int) sent[i];
    cout << "Your sentence in all lower case: "<< sent;
    cout << endl;
    if (current >= 65 && current <= 90)
    {
        current += 32;
        sent[i] = (char) current;
        cout << "Your sentence in all upper case: " << sent;
    }
    }

return 0;

}

输出应为:

请输入一句话:我吃苹果!

小写的句子:我吃苹果!

大写句子:我吃苹果!

但是,我一直使用小写字母“i”,使用大写字母“i”时,为什么我的代码无法打印出完整的句子?我不知道我做错了什么,或者做错了什么。

最佳答案

输入运算符>>在空格(空格,换行符,制表符等)上分隔。如果要阅读整行,请使用 std::getline :

cout << "Please enter a sentence: ";
getline(cin, sent);

无关紧要的是,请勿使用magic numbers65之类的 32 。如果您指的是字符,则使用实际的字 rune 字,例如'A''a' - 'A'(请注意,例如'a' - 'A'在所有编码中均无效,它以ASCII格式工作,这是最常见的编码,但它实际上不可移植)。这也假设这是学校的作业,否则您应该使用例如standard algorithm function和一些合适的ojit_a。

09-10 00:46
查看更多