问题
This does not work. I'm trying to learn how to use std::copy but I can't find any working code. I ran this in gcc 4.6.1. And it does not do anything when I hit control D. If I hit Control C...it prints out the new lines only.
Found code here:
Printing an array in C++?
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> userInput;
// Read until end of input.
// Hit control D
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(userInput)
);
// Print in Normal order
std::copy(userInput.begin(),
userInput.end(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
// Print in reverse order:
std::copy(userInput.rbegin(),
userInput.rend(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
}
回答1:
Not sure how you're running it or what you're entering but that seems to run fine for me:
pax$ g++ -o qq qq.cpp ; ./qq
1
2
3
4
5
0
9
8
7
6
<CTRL-D>
1,2,3,4,5,0,9,8,7,6,
6,7,8,9,0,5,4,3,2,1,
This is with gcc 4.3.4 under Cygwin. One thing to watch out for is that (in my environment at least), CTRL-D
has to be entered on a new line. Entering:
1 2 3 4 5<CTRL-D>
didn't work for me (the CTRL-D
was ignored) but:
1 2 3 4 5
<CTRL-D>
did.
You can bypass those issues with CTRL-D
by doing something like:
echo 1 2 3 4 5 6 7 8 9 0 | ./qq
so that end of file does not depend on your terminal characteristics. This is especially important since it may be that MinGW (being a Windows application rather than running under CygWin's emulation layer) requires the Windows end-of-file character, CTRL-Z
.
Running this command acts as expected:
pax$ echo 1 2 3 4 5 6 7 8 9 0 | ./qq
1,2,3,4,5,6,7,8,9,0,
0,9,8,7,6,5,4,3,2,1,
来源:https://stackoverflow.com/questions/7975320/a-working-stdcopy-example-printing-an-array