"从int到char的截断"没有产生任何结果

时间:2014-09-30 21:47:21

标签: c++ char int

我的代码可以编译,但它不会返回所请求的字符,并且它也不会遵循else语句,因为它会在来自true if语句的任何输入之后输出错误消息。 C ++初学者,所以感谢任何帮助。

// Python Challenge 2.cpp : This program will take a line of text from the user and then translate each letter 2 over in the alphabet.
//

#include "stdafx.h"

#include <iostream>

using namespace std;
char chChar; 
char chChar2;
char chChar_a;
char chChar_b;
int main()
{ 
    //This takes the one letter input from the user:
    cout << "Type in a lowercase letter: ";
    cin >> chChar;

    //for letters a-x
    if ((int)chChar >= 97 && (int)chChar <= 120)
        char chChar2 = (int)chChar + 2; 
        cout <<  "is now: " << chChar2 << endl;

        //for the letter y
        if ((int)chChar == 121)
        {
            char chChar_a = '97';
            cout <<  "is now: " << chChar_a << endl;
        }

        //for the letter z 
        if ((int)chChar == 122)
        {
            char chChar_b = '98';
            cout <<  "is now: " << chChar_b << endl;
        }   

    //for everything else
    else
        cout << "Error: type in a lowercase letter." << endl;

        return 0;   
}   

1 个答案:

答案 0 :(得分:0)

您的if声明不正确:您忘记在其后使用{ }创建一个块。

目前,代码确实:

//for letters a-x
if ((int)chChar >= 97 && (int)chChar <= 120)
{
    char chChar2 = (int)chChar + 2; 
}
// Always runs the next part
cout <<  "is now: " << chChar2 << endl;
...

最终else附加到if之前:

//for the letter z 
if ((int)chChar == 122)
{
    char chChar_b = '98';
    cout <<  "is now: " << chChar_b << endl;
}   
else
{
    cout << "Error: type in a lowercase letter." << endl;
}

要解决此问题,请添加适当的括号{ }。没有括号的if只有条件地执行下一个语句,而不是块 - 不要让缩进欺骗你:它们在C中没有意义。


因此,使用此功能,您的固定代码应如下所示:

//This takes the one letter input from the user:
cout << "Type in a lowercase letter: ";
cin >> chChar;

//for letters a-x
if ((int)chChar >= 97 && (int)chChar <= 120)
{
    char chChar2 = (int)chChar + 2; 
    cout <<  "is now: " << chChar2 << endl;

    //for the letter y
    if ((int)chChar == 121)
    {
        char chChar_a = '97';
        cout <<  "is now: " << chChar_a << endl;
    }

    //for the letter z 
    if ((int)chChar == 122)
    {
        char chChar_b = '98';
        cout <<  "is now: " << chChar_b << endl;
    }   
}
//for everything else
else
{
    cout << "Error: type in a lowercase letter." << endl;
}

return 0;   

从此开始,您可以调试代码以进一步解决问题。