ASCII和isalpha if语句问题

ASCII and isalpha if statement issue

本文关键字:语句 问题 if isalpha ASCII      更新时间:2023-10-16

我正在编写一个程序,它接受用户输入的字符,例如a,以及用户输入的数字,例如7。程序检查字符的有效性,如果为true则一直运行到函数内的这个循环。我在函数内部使用ascii十进制循环。这个循环需要检查isalpha,如果它运行了{}中的代码,它就正确地执行了。其他的工作方式不是我想要的,我不知道如何纠正它。我需要else(不是alpha)将1添加回循环中的计数器并将ascii值增加1。如果我这样运行它,它会发出重试/忽略/中止错误。如果我不使用num++;它运行并在循环结束后停止。所以,如果你输入一个Z并选择3,它会通过循环运行3次,并且只输出一个Z。有什么想法来解决这个问题吗?

我需要它输出类似:输入:Z输入:4它应该输出:Z A B C到屏幕。它需要忽略其他ascii非alpha字符。

感谢
string buildSeries(char A, int num)
{
//builds the output with the info the
//user inputted
stringstream str1;
string outted;
int DeC=(int)A, i = 0;
//loop builds the output
for(i=0;i<num;i++)
{

        if (isalpha(DeC))
        {
            //converts the decimal to a letter
            str1<<(char)DeC;
            //adds a space
            str1<<" ";
            //increases the decimal
            DeC++;
        }
        else
        {
        num++;
        DeC++;
        }

}
    //builds the sstream and puts it in
    //variable "outted"
    outted = str1.str();

return outted;

}

如果您需要在Z处循环回'A',请将DeC++更改为

if DecC == 'Z'
    DecC = 'A'
else
    DecC++;

或者你也可以使用模数运算符

编辑

我认为问题可能是这个stringstream插入操作符>>没有处理char类型的重载。它将char转换为short或int类型,然后插入它。尝试使用string::append(size_t size, char c)代替。它应该处理插入一个字符。

那就是用outted.append(1, (char)DeC)代替你对str1<<(char)DeC;的调用,并删除你对字符串流

的使用

什么是DeC?短语"ascii列表"让我怀疑它是一个'C'字符串,在这种情况下,你正在调用指针上的isAlpha(),而不是在字符串中的值。

编辑:如果你有

char DeC[40];
// read in a string form somewhere
// DeC is a pointer to some memory it has a value of a 32 or 64bit number
if ( isAlpha(DeC) {
// what you might have meant is 
if ( isAlpha(*DeC) { // the character value at the current position in DeC