2009-10-13 58 views
2

我顯然不是很接近C++的'文件結束'概念,因爲下面的程序只是沒有越過「while(cin >> x) 「 步。每當我從命令行運行它時,它都會嘲笑我。C++程序沒有移動過去的字符串輸入cin步驟

通過SO和其他地方的搜索提供了很多提及點擊CTRL-Z然後點擊輸入在窗口上通過文件結束字符,但這似乎並沒有爲我工作。這讓我認爲我的問題在別處。也許把x定義爲一個字符串是我的錯誤?任何關於我在哪裏出錯的建議都會很棒。

注意:對於代碼中缺少評論感到抱歉 - 程序本身應該採取一系列 單詞,然後吐出每個單詞的計數。

#include <iostream> 
#include <string> 
#include <vector> 
#include <algorithm> 
#include <iomanip> 

using std::cin; 
using std::cout;   using std::endl; 
using std::sort; 
using std::string;   using std::vector; 

int main() 
{ 
    cout << "Enter a series of words separated by spaces, " 
      "followed by end-of-file: "; 

    vector<string> wordList; 
    string x; 
    while (cin >> x) 
      wordList.push_back(x); 

    typedef vector<string>::size_type vec_sz; 
    vec_sz size = wordList.size(); 
    if (size == 0) { 
     cout << endl << "This list appears empty. " 
         "Please try again." << endl; 
     return 1; 
    } 

    sort(wordList.begin(), wordList.end()); 

    cout << "Your word count is as follows:" << endl; 
    int wordCount = 1; 
    for (int i = 0; i != size; i++) { 
     if (wordList[i] == wordList[i+1]) { 
      wordCount++; 
      } 
     else { 
      cout << wordList[i] << " " << wordCount << endl; 
      wordCount = 1; 
      } 
     } 
    return 0; 
} 
+0

肯定地發表一個新問題,對已經有一個可接受的答案的問題的評論中的後續操作不會獲得許多意見。 – 2009-10-13 18:50:20

回答

3

如果你在windows^Z必須作爲換行符之後的第一個字符出現,如果你在unixy shell中,那麼你想輸入^ D。

+1

您可能需要在^ Z或^ D後點擊 ... – 2009-10-13 17:12:53

0

我使用CIN時幾乎總是使用函數getline(特別是當我想要的是一個字符串):

istream& std::getline(istream& is, string& s); 

所以,你會打電話getline(cin, x),它會抓住一切都交給換行符。無論如何,你必須等待cin的換行符給你任何東西。所以,在這種情況下,你的循環將成爲:

while(getline(cin, x)) 
    wordList.push_back(x); 
0

cin不接受空格或換行符所以,除非你輸入一些的cin執行不會完成,這裏是一個測試程序,你想要的東西,讓你

#include "stdafx.h" 
#include<iostream> 
#include <string> 
#include <sstream> 

using namespace std; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    string str = ""; 
    while(std::getline(cin, str) && str!="") 
    { 
     cout<<"got "<<str<<endl; 
    } 
    cout<<"out"<<endl; 
    cin>>str; 
    return 0; 
} 
1

代碼的輸入部分起作用。唯一真正的問題,我看到的是與環路試圖計數的話:

for (int i = 0; i != size; i++) { 
    if (wordList[i] == wordList[i+1]) { 

從0到size-1個詞表運行有效下標。在循環的最後一次迭代中,i = size-1,但是然後嘗試使用wordList[i+1],超出矢量的末尾索引並得到未定義的結果。如果您改用wordList.at(i+1),它會拋出異常,並快速告訴您更多有關該問題的信息。

我的猜測是,發生的事情是,你正在擊中Control-Z,它正在退出輸入循環,但是當它試圖計算單詞時崩潰,所以當你修復這些問題時通常會更好。如果在解決其他問題(s?)之後確實無法超越輸入循環,並且您在Windows下運行,則可以嘗試使用F6而不是輸入control-Z--它似乎更可靠一些。