c ++使用指针以相反的顺序显示句子 [英] c++ displaying sentences in reverse order using pointers

查看:147
本文介绍了c ++使用指针以相反的顺序显示句子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立一个程序,从用户的短句,并以相反的顺序显示它们。不幸的是,我刚刚开始c ++我需要知道这样做。
例如:如果用户输入输入:

 我喜欢红色
蓝色也很好
和green是可爱的
,但是我不喜欢橙

/ p>

 但我不喜欢橙色
和绿色是可爱的
蓝色也很不错
我喜欢红色

提前感谢!

 #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 {

cout<<输入字符串:;
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 ='\0';
cout<< reverse<< endl;


系统(PAUSE);
return 0;
}


解决方案

意图接近这是以下算法:


  1. 将文件加载到缓冲区中,使用空字符终止它。

  2. 将指针 p 定位到最后一个缓冲槽位置。

  3. p 不指向缓冲区的开头,请执行以下操作:

    • 如果字符是换行符('\\ \\ n'换行符( p + 1 ) / code>)到stdout。

    • 使用空字符覆盖 p 指向的换行符。


  • 减少 p 返回一个字符位置。


  • 完成上述循环后,剩余一行:第一行。


  • 因此我得以相信。需要考虑的重要事项如下:


    1. 算法是否使用空文件?


    2. 该算法是否适用于没有尾随换行符的多行文件?


    3. 算法是否使用带有尾随换行符的多行文件运行?

    4. 算法使用单行文件和尾随换行符?

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

      #include< iostream> 
    #include< fstream>
    #include #include< vector>
    using namespace std;

    int main(int argc,char * argv [])
    {
    //假定文件反向打印是第一个
    //命令行参数。如果我们没有一个
    //我们现在需要离开。
    if(argc <2)
    return EXIT_FAILURE;

    //将保存我们的文件数据
    std :: vector< char>数据;

    //打开文件,关闭空格跳过
    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; //终止符

    //向后移动缓冲区。在每个换行符,发送
    //一切*过去*它到stdout,然后用nullchar(0)覆盖
    //换行字符,然后继续。
    char * start =& data [0];
    char * p = start +(d​​ata.size() - 1);
    for(; p!= start; --p)
    {
    if(* p =='\\\
    ')
    {
    if(* p + 1))
    cout<< (p + 1)<< endl;
    * p = 0;
    }
    }

    //最后一行(第一行)
    cout<< p < endl;

    return EXIT_SUCCESS;
    }

    输入

     我喜欢红色
    蓝色也很好
    和绿色是可爱的
    但是我不喜欢橙色

    输出

     但我不喜欢橙色
    和绿色是可爱的
    蓝色也很好
    我喜欢红色






    更简单的方法



    很多 更简单的方法可以做到这一点,我将解释评论中的每一步。有机会,您不能使用这样的东西,但重要的是你明白你可以有什么:

      #include< iostream> 
    #include< fstream>
    #include #include< vector>
    using namespace std;

    int main(int argc,char * argv [])
    {
    //假定文件反向打印是第一个
    //命令行参数。如果我们没有一个
    //我们现在需要离开。
    if(argc <2)
    return EXIT_FAILURE;

    //将保存我们的文本行的集合
    vector< string>线;

    //一次读取一行,直到没有返回
    //将每一行都拖入我们的向量。
    ifstream inf(argv [1]);
    string line;
    while(getline(inf,line))
    lines.push_back(line);
    inf.close();

    // a LOT发生在下一行代码中,
    //我将尝试描述每一步。
    //
    //我们使用std :: copy()从
    中复制所有的items//开始和结束迭代器对。复制的
    //目标是另一个迭代器。
    //
    //我们的目标迭代器为我们的格式化的输出
    //是一个特殊的迭代器类设计为
    //执行输出流插入操作
    / /(这是<<运算符)到流是
    //使用每个
    //项目构造的(在我们的例子中是cout),我们从我们的复制迭代中给出它。使用
    //这个类的复制项目必须支持
    //传统的插入运算符<<,
    // course,std :: string。在每个项目是
    //之后,提供的后缀(在我们的例子中为\\\

    //也被写入。没有这一切所有的行
    //将被联合在一起。
    //
    //最后,为了将这些粘合在一起(和整个
    //原因我们在这里),我们使用一对特殊的
    //迭代器工作就像你熟悉的常规
    // begin()和end()迭代器,
    //当在顺序中向前移动时,但是这些
    // ones,rbegin )和rend(),从序列中的最后
    //项目移动到第一个项目,这是
    // * exactly *我们需要的。

    copy(lines.rbegin(),lines.rend(),
    ostream_iterator< string>(cout,\\\
    ));

    //就是这样。
    return EXIT_SUCCESS;
    }

    输入

     我喜欢红色
    蓝色也很不错
    和绿色是可爱的
    ,但我不喜欢橙色

    输出

     但我不喜欢橙色
    和绿色是可爱的
    蓝色也很好
    我喜欢红色






    UPDATE:合并用户输入 b

    合并第二个版本的用户输入的示例是:

      #include< iostream> ; 
    #include #include< vector>
    using namespace std;

    int main(int argc,char * argv [])
    {
    //将保存我们的文本行的集合
    vector< string&线;
    do
    {//提示用户
    cout<< Sentance(< enter> to exit):;
    string line;
    if(!getline(cin,line)|| line.empty())
    break;
    lines.push_back(line);
    } while(true);

    //使用反向迭代器发送回输出
    //切换行顺序。
    copy(lines.rbegin(),lines.rend(),
    ostream_iterator< string>(cout,\\\
    ));

    return EXIT_SUCCESS;
    }


    i'm trying to build a program that takes short sentences from the user and display them in reverse order. unfortunately, I just began c++ I need to know to do that. for example: if user entered input:

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

    output:

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

    Thanks in advance!

    #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 = '\0';
        cout << reverse<<endl;
    
    
       system("PAUSE");
       return 0;
    }
    

    解决方案

    A considerable way you're intended to approach this is the following algorithm:

    1. Load the file into a buffer, terminating it with a null char.
    2. Position a pointer p to the location of the last buffer slot.
    3. While p is not pointing to the start of the buffer do the following:
      • If the character is a newline ('\n') then

        1. Send the string past the newline (p+1) to stdout.
        2. Overwrite the newline pointed to by p with a null char.

      • Decrement p back one char position.
    4. After the above loop is finished there is one line remaining: the first one. send it to stdout and you're done.

    Or so I am led to believe. Important things to consider are the following:

    1. Does the algorithm work with an empty file?
    2. Does the algorithm work with a file containing ONLY newlines?
    3. Does the algorithm work with a multi-line file WITH NO trailing newline?
    4. Does the algorithm work with a single line file WITH NO trailing newline?
    5. Does the algorithm work with a multi-line file WITH trailing newline?
    6. Does the algorithm work with a single line file WITH trailing newline?

    That being said, here is a potential candidate:

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

    Input

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

    Output

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


    A Considerably Simpler Approach

    There are much simpler ways to do this, and I'll explain each step in comment along the way. Chance are you can't use something like this, but it is important you understand what is available to you when you can:

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

    Input

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

    Output

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


    UPDATE: Incorporating User Input

    An example of incorporating user input for the second version would be:

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

    这篇关于c ++使用指针以相反的顺序显示句子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆