C++ 使用指针以相反的顺序显示句子

c++ displaying sentences in reverse order using pointers

本文关键字:顺序 显示 句子 指针 C++      更新时间:2023-10-16

我正在尝试构建一个程序,该程序从用户那里获取短句并以相反的顺序显示它们。 不幸的是,我刚刚开始C ++我需要知道这样做。例如:如果用户输入:

I like the red color
blue is also nice
and green is lovely
but I don't like orange

输出:

but I don't like orange
and green is lovely
blue is also nice
I like the red color

提前感谢!

#include<iostream>
#include<string>
using namespace std;
const int SIZE= 500;
int main()
{
   const int SIZE = 500;
   char mystring[SIZE];
int i;
for(i=0; i<SIZE; i++)
{
    cout<<"Enter a string: ";
    cin.getline(mystring, SIZE);
    } while (mystring != 0);
       char * reverse= new char[strlen(mystring) + 1];
        char *p1 = mystring+ strlen(mystring);
        char *p2 = reverse;

        while(p1 != mystring)
        {
        p1--;
        *p2= *p1;
        p2++;
    }
    *p2 = '';
    cout << reverse<<endl;

   system("PAUSE");
   return 0;
}

您打算解决此问题的一种相当多的方法是以下算法:

  1. 将文件加载到缓冲区中,并以空字符终止该文件。
  2. 将指针放置在p最后一个缓冲区插槽的位置。
  3. p不指向缓冲区的开头时,请执行以下操作:
    • 如果字符是换行符 ( 'n' (,则
      1. 将字符串通过换行符 ( p+1 ( 发送到标准输出。
      2. 用空字符覆盖 p 指向的换行符。
    • 递减p回一个字符位置。
  4. 上述循环完成后,还剩下一行:第一行。 将其发送到标准输出,您就完成了。

或者说,我被引导相信。需要考虑的重要事项如下:

  1. 该算法是否适用于空文件?
  2. 该算法是否适用于仅包含换行符的文件?
  3. 该算法是否适用于没有尾随换行符的多行文件?
  4. 该算法是否适用于没有尾随换行符的单行文件?
  5. 该算法是否适用于带有尾随换行符的多行文件?
  6. 该算法是否适用于带有尾随换行符的单行文件?

话虽如此,这里有一个潜在的候选人:

#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
    // assume the file to reverse-print is the first
    //  command-line parameter. if we don't have one
    //  we need to leave now.
    if (argc < 2)
        return EXIT_FAILURE;
    // will hold our file data
    std::vector<char> data;
    // open file, turning off white-space skipping
    ifstream inf(argv[1]);
    inf.seekg(0, inf.end);
    size_t len = inf.tellg();
    inf.seekg(0, inf.beg);
    // resize buffer to hold (len+1) chars
    data.resize(len+1);
    inf.read(&data[0], len);
    data[len] = 0; // terminator
    // walk the buffer backwards. at each newline, send
    //  everything *past* it to stdout, then overwrite the
    //  newline char with a nullchar (0), and continue on.
    char *start = &data[0];
    char *p = start + (data.size()-1);
    for (;p != start; --p)
    {
        if (*p == 'n')
        {
            if (*(p+1))
                cout << (p+1) << endl;
            *p = 0;
        }
    }
    // last line (the first line)
    cout << p << endl;
    return EXIT_SUCCESS;
}

输入

I like the red color
blue is also nice
and green is lovely
but I don't like orange

输出

but I don't like orange
and green is lovely
blue is also nice
I like the red color

相当简单的方法

更简单的方法可以做到这一点,我将在此过程中在注释中解释每个步骤。您有可能不能使用这样的东西,但重要的是,当您可以执行以下操作时,了解您可以使用的内容:

#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
    // assume the file to reverse-print is the first
    //  command-line parameter. if we don't have one
    //  we need to leave now.
    if (argc < 2)
        return EXIT_FAILURE;
    // collection that will hold our lines of text
    vector<string> lines;
    // read lines one at a time until none are returned
    //  pushing each line in to our vector.
    ifstream inf(argv[1]);
    string line;
    while (getline(inf, line))
        lines.push_back(line);
    inf.close();
    // a LOT happens in the next single line of code, and
    //  I will try to describe each step along the way.
    //
    // we use std::copy() to copy all "items" from
    //   a beginning and ending iterator pair. the
    //   target of the copy is another iterator.
    //
    //  our target iterator for our formatted ouput
    //   is a special iterator class designed to
    //   perform an output-stream insertion operation
    //   (thats the << operator) to the stream it is
    //   constructed with (in our case cout) using each
    //   item we give it from our copy-iteration. to use
    //   this class the "copied" item must support the
    //   traditional insertion operator <<, which of
    //   course, std::string does. after each item is
    //   written, the provided suffix (in our case n)
    //   is written as well. without this all the lines
    //   would be ganged together.
    //
    //  lastly, to glue this together (and the whole
    //   reason we're here), we use a pair of special
    //   iterators designed to  work just like the regular
    //   begin() and end() iterators you're familiar with,
    //   when traversing forward in a sequence, but these
    //   ones, rbegin() and rend(), move from the last
    //   item in the sequence to the first item, which is
    //   *exactly* what we need.
    copy(lines.rbegin(), lines.rend(), 
         ostream_iterator<string>(cout, "n"));
    // and thats it.
    return EXIT_SUCCESS;
}

输入

I like the red color
blue is also nice
and green is lovely
but I don't like orange

输出

but I don't like orange
and green is lovely
blue is also nice
I like the red color

更新:合并用户输入

为第二个版本合并用户输入的示例如下:

#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
    // collection that will hold our lines of text
    vector<string> lines;
    do
    {   // prompt the user
        cout << "Sentance (<enter> to exit): ";
        string line;
        if (!getline(cin, line) || line.empty())
            break;
        lines.push_back(line);
    } while (true);
    // send back to output using reverse iterators
    //  to switch line order.
    copy(lines.rbegin(), lines.rend(),
         ostream_iterator<string>(cout, "n"));
    return EXIT_SUCCESS;
}

也许是这样的:

#include <string>
#include <iostream>
#include <vector>
using namespace std;
// include headers and avoid having to use std:: all the time
int main(){
    vector<string> data;
    string line;
    do{
        std::getline(std::cin, line);
        data.push_back( line );
    }while( cin );//read lines and store to a vector
    for (int i=data.size()-1;i>=0;--i)// traverse the vector in a reversed order (maybe size_t for i would be better)
        cout<<data[i]<<endl;
}

看起来这是一些家庭作业,可能您只能使用某些功能。如果你坚持,我们可以写一个家庭作业安全版本:

// this is just intended to illustrate how RIDICULOUS it is not to use STL features.
#include <cstring>
#include <cstdio>
#include <cstdlib>
int main(){
#define MAXLEN (10000)
    char* buffer = (char*)malloc(MAXLEN);//allocate space from heap
    char* buffer_ptr = buffer + 1;
    *buffer = '';//string terminator
    while( fgets(buffer_ptr,buffer+MAXLEN-buffer_ptr , stdin ) ){
        buffer_ptr += strlen(buffer_ptr);
        ++buffer_ptr;// reserve the ''
    }
    buffer_ptr -= 2;
    while(buffer_ptr >= buffer){
        if (!*buffer_ptr)// find end of string
            fputs(buffer_ptr+1,stdout);
        --buffer_ptr;// traverse backward
    }
    free(buffer);//free space
}

尽可能避免C++扩展。(以一种可能荒谬的方式(

#include<iostream>
using namespace std;
int main(){
    char str[100][100];
    for(int i =0; i < 10 ; i++) {
        cin.getline(str[i],100);
    }
    for(int i = 9 ; i >=0 ; i--) {
        cout<<str[i]<<endl;
    }
}

这就是如何做得漂亮。

template<class It>
struct range_t {
  It b; It e;
  It begin() const { return b; }
  It end() const { return e; }
};
template<class It>
range_t<It> range(It s, It f) {
  return {s,f};
}

range( start, finish )是一个帮助程序,可用于创建可for(:)迭代的范围。

template<class C>
auto backwards(C&& c) {
  using std::rbegin; using std::rend;
  return range( rbegin(c), rend(c) );
}

backwards(container)返回一个向后迭代容器的范围。

一旦我们编写了上面的库代码,所有繁重的工作就完成了。 其余的代码读起来几乎和python一样漂亮:

int main() {
  std::cout << "Enter some text (blank line to finish):n";
  std::string line;
  std::vector<std::string> lines;
  while (std::getline(std::cin, line))
    lines.push_back(line);
  for (auto&& line:backwards(lines))
    std::cout << line << "n";
}

我们得到线条,缓冲它们,然后向后打印它们。

活生生的例子。

这里的目标是使主程序逻辑尽可能清晰。 backwardsrange样板只是满足了这一需求。