2012-08-03 81 views
0

我從Robert Sedwick有關算法的書中獲得以下代碼。如何在C++中使用cin退出

怎樣在下面的語句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; 
    } 
+0

對不起,但這是一個很不清楚的問題。你想要做什麼以及哪些方面不起作用? – 2012-08-03 12:16:37

+0

你的問題是什麼? – 2012-08-03 12:16:45

+0

我認爲問題出在標題上,而不是信息的內容。看來Bo已經在下面回答了。 – RageD 2012-08-03 12:17:36

回答

8

打破一個循環如果您在控制檯輸入的輸入,必須輸入結束文件中的代碼。

對於Linux,這將是Ctrl+D,以及對於Windows Ctrl+Z

+2

值得一提的是,替代方法是在shell中提取('|')或提取文件('<')。 – Potatoswatter 2012-08-03 12:18:33