【问题标题】:How to add a question mark to the end of a line?如何在行尾添加问号?
【发布时间】:2013-04-27 04:32:27
【问题描述】:

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

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

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

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

strcpy(current->data,buffer);

}

【问题讨论】:

  • 这是一个 C 问题,在 C++ 中你不会直接操作缓冲区
  • 你真的需要将它添加到缓冲区本身,还是只需要在 current->data 的末尾加上问号?
  • @rhalbersma - 虽然这是一个 C 问题,但您评论的第二部分不一定正确。发帖人可能正在大型 C++ 应用程序中编写 C 风格的代码,或者打算将其提供给 C++ 编译器。
  • @RichardTeviotdale C 也有operator->
  • 它是一个 C++ 程序。我只需要在 current->data 的末尾加上问号,我想修改缓冲区会更容易。

标签: c++ c parsing buffer


【解决方案1】:

据我所知,以这种方式修改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()

【讨论】:

  • tiny nitpick: buffer.size() 可以写成更惯用的!buffer.empty()
  • @rhalbersma:完成。我认为最好保持与原始代码相同的“逻辑”,但!empty() 更清晰。
  • 逻辑没有改变,只有语法,我同意现在更清楚了,所以 +1 :-)
【解决方案2】:

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

//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

【讨论】:

    猜你喜欢
    • 2016-04-13
    • 2022-11-22
    • 1970-01-01
    • 2017-04-28
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多