-1

帮助我知道它有什么问题,因为我只是一个初学者,我正在尝试构建一个程序,要求用户输入短句,直到用户退出并以相反的顺序显示它们:示例用户输入:

My name is Todd
I like to travel

并像这样显示:

I like to travel
My name is Todd

任何人都可以帮助我使其正常工作;它可以正常工作,但不会在执行后立即退出。我希望能够抓住窗户。提前致谢

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

int main(int argc, char *argv[])
{
    const int SIZE = 500;
    char input[SIZE];

    // collection that will hold our lines of text
    vector<string> lines;
    do
    {   // prompt the user
        cout << "Enter a short sentence(<enter> to exit): ";
        cin.getline(input,SIZE);
        if (!getline(cin, input) || input.empty())
            break;
        lines.push_back(input);
    } while (true);

    // send back to output using reverse iterators
    //  to switch line order.
    copy(lines.rbegin(), lines.rend(),
         ostream_iterator<string>(cout, "\n"));
      // 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
    cin>>(argv[1]);
    cin.seekg(0, cin.end);
    size_t len = cin.tellg();
    cin.seekg(0, cin.beg);

    // resize buffer to hold (len+1) chars
    data.resize(len+1);
    cin.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;
}
4

2 回答 2

1

I managed to get this to work by using std::string in place of char input[SIZE]. I also removed the cin.getline part in the loop because it's not really needed.

std::string input;

do {
    // cin.getline(input, SIZE); <-- removed this line
    if (!getline(cin, input) || input.empty())
       break;
    lines.push_back(input);
} while (true);

See a demo here.

于 2013-02-18T02:27:23.347 回答
0

既然您说它工作正常...(也许您应该考虑将其添加到您的帖子中,而不仅仅是在评论中)

您需要在执行完成后按住窗口。

然后,这很简单。

#include <cstdlib>
// whatever.....
int main(){
  ......//whatever 
   .......//foo
    .......//bar
  system("pause"); // hold the window
}

system()用虚拟无限循环替换应该也可以,这可以节省但#include <cstdlib>会消耗 CPU 时间。

于 2013-02-18T02:48:19.883 回答