我正在写一个程序,它接受用户输入的字符,如A,和用户输入的数字,如7。该程序检查字符的有效性,如果为真,则遍历,直到它到达函数内部的这个循环。我在函数中使用了ascii decimal作为这个循环。这个循环需要检查isalpha,如果它在{}中运行代码,那么它就是正确的。else不是我想要的工作方式,不确定如何纠正它。我需要else (不是alpha)将1加回到循环中的计数器中,并将ascii加1。如果我这样运行它,它会发出一个重试/忽略/中止错误。如果我在不使用num++的情况下运行它,它会在循环结束后运行并停止。所以,如果你输入一个Z并选择3,它会在循环中运行3次,只输出一个Z。你有没有想过如何解决这个问题?
我需要它输出一些东西,比如: Input: z Input: 4它应该输出:Z,B,C到屏幕。它需要忽略其他ascii非字母字符。
谢谢
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;}
发布于 2011-10-18 04:22:21
如果需要循环回到Z处的'A‘,请将DeC++更改为
if DecC == 'Z'
DecC = 'A'
else
DecC++;或者你可以使用模运算符
编辑
我认为问题可能是这个stringstream insertion operator,>>,没有处理字符的重载。它将字符转换为短整型或整型,然后插入。请尝试使用string::append(size_t size, char c)。这应该可以处理插入字符。
也就是说,将对str1<<(char)DeC;的调用替换为outted.append(1, (char)DeC),并删除对字符串流的使用
发布于 2011-10-18 04:10:39
什么是DeC?短语"ascii list“让我怀疑它是一个'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 DeChttps://stackoverflow.com/questions/7798895
复制相似问题