【问题标题】:Why doesn't the for loop do what I wrote in the program? [closed]为什么 for 循环不执行我在程序中编写的内容? [关闭]
【发布时间】:2023-01-26 21:01:25
【问题描述】:

我想制作一个程序,使句子中单词的每个首字母大写(没有 toupper)。 但出于某种原因,for 循环没有按照我的意愿执行。该程序只是跳过for 循环。 我从不在其他任何地方使用i。只针对循环和我在循环中写的东西。

顺便说一句,这是程序作为一个整体应该做的事情。

  1. 初始化iSentence(当然是两种不同的数据类型)

  2. 让用户输入选择的小写句子(包括空格)

  3. 检查首字母是否为小写(ASCII 码从 97 到 122)

  4. 首字母大写,因为第一个单词前没有空格(将在下一步中解释)

  5. for 循环中,检查后面的字母是否为空格(ASCII 码 32)

  6. 然后,检查下一个字母 i++ 是否为小写字母(ASCII 码从 97 到 122)

  7. 如果所有这些都是正确的,程序会从该字母中减去 32(32 是小写字母和大写字母的每个 ASCII 码之间的差值,例如:a(ASCII 码 97)- 32 = A(ASCII 码 65))

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main(){
        int i;
        string Sentence;
        getline(cin, Sentence);
            if(Sentence[0] >= 97 && Sentence[0] <= 122)
                Sentence[0] = Sentence[0] - 32;
        for(i = 0; i <= Sentence.length() - 1; i++) // I'm talking about this loop
            if(Sentence[i] == 32)
                if(Sentence[i++] >= 97 && Sentence[i++] <= 122)
                    Sentence[i++] = Sentence[i++] - 32;
    
    
    
        cout << Sentence;
    
        return 0;
    }
    

    我用固定数字试过了,它起作用了。我没有使用任何循环,我只是手动重复 我上传了两张图片,有和没有 for 循环。

    Here it is without the loop.

    Here it is with the loop.

    我该怎么办?

【问题讨论】:

  • 每个i++ 都会递增i。您不希望 i 增加 4 倍,是吗?
  • i++ 修改 i - 因为您在循环中最多调用 4 次,所以它访问的方式超出了您想要的下一个字符
  • 第二次查看时,检查将在 Sentence[i++] &gt;= 97 处失败,因为您再次检查相同的字符(您已经确定为 32,因此小于 97),因为 i++ 返回了 @987654343 的先前值@
  • 为什么不对照 Sentence.size() 检查 i++?而不是 97 使用 'a'

标签: c++ loops for-loop uppercase


【解决方案1】:

当遍历你的循环时,你通过使用递增运算符直接修改i++。您正在执行循环(递增 i 本身),并在检查 Sentence[i++] 时递增 ii += 1,然后在 i 的索引处访问 Sentence。要解决此问题,请删除增量运算符:

for(i = 0; i <= Sentence.length() - 1; i++)
        if(Sentence[i] == 32)
            if(Sentence[i] >= 97 && Sentence[i] <= 122)
                Sentence[i] = Sentence[i] - 32;

但是随后代码变得多余,因为我们正在检查 if sentence[i] == 32,并且在 if 子句中:我们知道永远不会运行的 if sentence[i] &gt;= 97。我假设当您使用:i++ 时,您想要访问下一个字符。使用:i + 1 来完成这个。

【讨论】:

  • 不过,if(Sentence[i] == 32) if(Sentence[i] &gt;= 97 &amp;&amp; Sentence[i] &lt;= 122) 不会做太多事情。你不能成为一个空间或其他东西
  • 正确的!没有仔细看道歉,将编辑。
猜你喜欢
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 2018-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多