更新时间:2023-11-17 23:26:58
我喜欢的模式是:
while (!cin.eof())
{
string line;
getline(cin, line);
if (cin.fail())
{
//error
break;
}
cout << line << endl;
}
与其他答案一样,您可以键入 CTRL + Z
将 EOF
发送到 STDIN
.如果 STDIN
是管道,则当流中没有更多数据时,将发送 EOF
.
As in the other answers, you can type CTRL+Z
to send an EOF
to STDIN
. If STDIN
is a pipe, then EOF
will be sent when the stream has no more data.
要保存到向量中:
vector<int> numbers;
while (!cin.eof())
{
string line;
getline(cin, line);
if (cin.fail())
{
//error
break;
}
cout << line << endl;
istringstream iss(line);
int num;
iss >> num;
numbers.push_back(num);
}
如果您想要C样式的数组(尽管我会推荐 std :: vector
:
If you want a C-style array (although I would recommend std::vector
:
size_t START_SIZE = 100;
size_t current_size = START_SIZE;
size_t current_index = 0;
int* numbers = new int[current_size];
while (!cin.eof())
{
string line;
getline(cin, line);
if (cin.fail())
{
//error
break;
}
cout << line << endl;
if (current_index == current_size)
{
current_size += START_SIZE;
int* tmp_arr = new int[current_size];
for (size_t count = 0; count < current_index; count++)
{
tmp_arr[count] = numbers[count];
}
delete [] numbers;
numbers = tmp_arr;
}
istringstream iss(line);
int num;
iss >> num;
numbers[current_index] = num;
current_index++;
}
delete [] numbers;