繁体   English   中英

如何在行尾添加问号?

[英]How to add a question mark to the end of a line?

我想检查用户是否添加了? 到缓冲区的末尾。 如果没有,我希望程序自动添加一个。 到目前为止,这就是我所拥有的。 我不知道下一步该怎么做。

首先,我检查缓冲区是否为空。
然后,如果最后一项不是? ,将问号自动添加到缓冲区中,然后将内容复制到当前数据节点。

if ( strlen(buffer) != 0)
{
   if (buffer[strlen(buffer)-1] != '?')
   {

           //what do i put here to add the ? if theres non?    
   }

strcpy(current->data,buffer);

}

据我所知,以这种方式修改buffer没有任何好处。 您可以简单地添加? 到当前- current->data如果需要)。

int len = strlen(buffer);
strcpy(current->data, buffer);
if (len && buffer[len-1] != '?') {
    current->data[len] = '?';
    current->data[len+1] = '\0';
}

如果可以选择,则应考虑更改代码以改为使用std::string

std::string buffer = input();
if (!buffer.empty() && buffer.back() != '?') buffer += '?';
std::copy(buffer.begin(), buffer.end(), current->data);
current->data[buffer.size()] = '\0';

如果您没有C ++ 11编译器,请使用*buffer.rbegin()而不是buffer.back()

您需要将字符串与用户正在写的带有问号one的消息进行串联。为此,您可以使用concatenate方法。本文介绍了此方法。 串联字符串无法正常工作

在连接问号之前,为什么不创建一个检查最后一个字符是否为问号的函数?

//Create function that returns a bool
bool isQuestionMark(char * buffer)
{  
    //Create pointer to buffer    
    char * pointer = buffer;

    //Go to the null character
    while(*pointer != '\0')
        pointer++;

    //Get to the last character
    pointer--;

    //Check to see if last character is a question mark
    if(*pointer == '?')
        return true;
    else
        return false;
}

然后,您想调用该函数以查看是否需要连接问号。

if(isQuestionMark(buffer) == true)
    strcat(buffer, "?");
else
    //Do nothing

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM