我从 Robert Sedwick 的一本关于算法的书中得到以下代码。
如何在以下语句中打破 for 循环if (!(cin >> a[N])) break;
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int compare(const void *i, const void *j)
{ return strcmp(*(char **)i, *(char **)j); }
int main()
{ const int Nmax = 1000;
const int Mmax = 10000;
char* a[Nmax]; int N;
char buf[Mmax]; int M = 0;
for (N = 0; N < Nmax; N++)
{
a[N] = &buf[M];
if (!(cin >> a[N])) break;
M += strlen(a[N])+1;
}
// std::cout << "Number of strings entered are " << N << std::endl;
qsort(a, N, sizeof(char*), compare);
for (int i = 0; i < N; i++)
cout << a[i] << endl;
}