c++ - 为什么我的代码一直打印 "i"而不是完整的句子?

标签 c++

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

#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 EAT APPLES!

但是我总是得到小写字母“i”表示小写字母,而大写字母则得到大写字母 I,为什么我的代码没有打印出完整的句子?我不明白我做错了什么或哪里做错了。

最佳答案

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

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

在不相关的说明中,请不要使用 magic numbers6532。如果您指的是字符,则使用实际的字 rune 字,例如 'A''a' - 'A'(请注意,例如 'a' - 'A ' 并非在所有编码中都有效,它适用于最常见的编码 ASCII,但它确实不可移植)。这也假设这是一项学校作业,否则您应该使用例如std::toupper和一些合适的standard algorithm function .

关于c++ - 为什么我的代码一直打印 "i"而不是完整的句子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35622275/

相关文章:

c++ - 将 RxCpp 库添加到 cmake 项目中

c++ - i + 1 < vec.size() 和 i < vec.size() - 1 之间的区别

c++ - 无法为 Typedef 声明好友

c# - 为什么从针对任何 CPU 的 C# 项目调用时,此代码会抛出 System.AccessViolationException?

c++ - 我如何迭代集合中的替代元素(或进行特定大小的跳跃)?

c++ - 第一个 cudaMalloc(K40 vs K20)的缓慢,即使在 cudaSetDevice 之后

c++ - 具有相同名称的静态变量的开关案例的单独范围

c++ - 需要帮助理解 "{}-initializer syntax minimizes the chances for unfortunate conversions"

c++ - 如何有效地并行化分而治之算法?

c++ - 如何用我的 C++ 项目实现 QuickFix