简体   繁体   中英

How to add a question mark to the end of a line?

I want to check to see if the user added a ? to the end of the buffer. If not, I want the program to add one automatically. This is what I have so far. I dont know what to do next.

First I check to see if the buffer is not blank.
Then, if the last item is not a ? , add the question mark automatically to the buffer and then copy the content to the current data node.

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

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

strcpy(current->data,buffer);

}

From what I can see, you don't gain anything from modifying buffer in this way. You can simply add the ? to current->data if it is needed.

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

If it is an option, you should consider changing your code to use std::string instead.

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

If you don't have a C++11 compiler, use *buffer.rbegin() instead of buffer.back() .

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

Why not create a function that checks whether or not the last character is a question mark before you concatenate the question mark?

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

Then you want to call that function to see if you need to concatenate a question mark.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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