0

这是我尝试输入,然后以相反的顺序产生单词的输出。注意:我只能使用指针。

    Input: What is your name? 
    Output: name? your is What

我查看了此处发布的其他解决方案,并试图尽可能多地实施它们,但我一直遇到问题。目前它只显示该行的第一个字母。我将不胜感激任何帮助解决它!

#include <iostream>
using namespace std;

#include <cstring>

int main( )
{
    char input[255] = {' '};
    char *head, *tail;
    char temp; 
    int i = 0; 

    cin >> input;

    head = input;
    tail = input;

    while(*tail!='\0')
    {
        tail++;
    }

    while (tail <= head){
        temp = *head;
        *head=*tail;
        *tail=temp;

        *head++;
        *tail--;
    }

    cout << input;
    cout << endl;

    return 0;
}
4

3 回答 3

3

尝试这个。没有任何参考 STL。

#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char **argv)
{
    char input[255];
    char *head; // head of a word.
    char *tail; // tail of a word.
    cin.getline(input, 255); // read a whole line.
    tail = input + strlen(input) - 1; // if you can use <cstring>?
    while (tail >= input) {
        if (*tail == 0 || *tail == ' ') {
            tail--; // move to the tail of a word.
        } else {
            tail[1] = 0;
            head = tail;
            while (head >= input) {
                if (head == input || *(head - 1) == ' ') {
                    cout << head << " "; // output a word.
                    tail = head - 1; // seek the next word.
                    break;
                }
                head--; // move to the head of a word.
            }
        }
    }
    cout << endl;
    return 0;
} 
于 2013-01-06T01:47:57.817 回答
1

像这样的伪代码怎么样:

read_input_into_string();
trim_leading_and_trailing_whitespace();
convert_multiple_whitespace_in_string_to_single_space();

for (char* current_string_ptr = find_end_of_string();
     current_string_ptr > start_of_input;
     current_string_ptr--)
{
    if (*current_string_ptr == ' ')
    {
        // +1 because `current_string_ptr` is at the space,
        // and we want to print the word without leading spaces
        std::cout << (current_string_ptr + 1) << ' ';

        // Terminate string at the space
        *current_string_ptr = '\0';
    }
}

它不完整(即不会打印输入中的第一个单词),但我将其作为练习留给读者。:)

于 2013-01-06T01:18:58.587 回答
0

低级:

void reverseStr(const char* str, char* szBuffer)
{
    int j = strlen(str) - 1, i = j, k = 0;
    if(j < 0)
        return;
    while(j >= 0){
        if(j-1 < 0 || *(str+j-1) == ' '){
            strncpy(szBuffer+k, str+j, i-j+1);
            szBuffer[k+i-j+1] = ' ';
            k += i-j+2;
            i = j-2;
            j -= 2;
        }
        else{
            --j;
        }
    }
    szBuffer[k-1] = '\0';
}

int main(int argc, char** argv)
{
    const char* str = "this is a string?";

    char szBuffer[256];
    reverseStr(str, szBuffer);

    std::cout << szBuffer;

}
于 2015-01-15T09:15:24.297 回答