2014-12-04 63 views
0
// ConsoleApplication25.cpp : main project file. 

#include "stdafx.h" 
#include <iostream> 
#include <string> 
#include <iomanip> 
#include <ios> 
#include <vector> 
#include <algorithm> 

using namespace System; 
using namespace std; 

int main() 
{ 
    vector<string> words; 
    string x; 

    cout << "Enter words followed by end of file: " << endl; 

    while (cin >> x){ 
     words.push_back(x); 
    } 
    cout << endl; 

    int count=0; 
    string Uword; 

    cout << "Enter the word you want me to count" << endl; 
    cin >> Uword; 

    for(int i = 0; i < (int)words.size(); ++i){ 
     if (Uword == words[i]){ 
      ++count; 
     } 

}我似乎无法得到v.push.back()的字符串

cout << "You word appeared " << count << " times" << endl; 

    system("pause"); 
    return 0; 
} 

可有一个人告诉我,我做错了什么工作? :/显然我不明白一个关键概念。该程序不断跳过我的第二个cin。甚至没有看到for循环,我也不知道为什么。

回答

0

您的第一个while循环读取到文件结束...文件结束后,您的流状态的EOF位已设置,这就是该循环退出的原因。这也是为什么下一次尝试cin >> Uword退出而没有做任何事情。如果你写了类似...

if (!(cin >> UWord)) 
{ 
    std::cerr << "unable to read uword from cin\n"; 
    return 1; 
} 

...(通常是一个好习惯),你会注意到失败。

的典型方法这个问题是有一个“哨兵”词,表示词的集合...例如结束:

std::cout << "Enter valid words followed by the sentinel <END>:\n"; 
while (std::cin >> x && x != "<END>") 
    words.push_back(x); 

你肯定会想使用if测试之后在阅读Uword时,您可以在没有看到<END>的情况下识别并处理已经命中的EOF。

或者,让他们进入Uword第一再让循环读取所有字运行,直到EOF ....

这是值得注意的是,对于一些copilers /环境,cin可以“体验”多个正交函数...用于例如,在Windows CMD.EXE提示符的其他空行上按Control-Z生成EOF,但如果您致电cin.clear()来重置EOF位,则可以在之后继续读取cin。这就是说,如果你写的程序就靠这个那么有没有办法自动调用/使用/ using语句一样对其进行测试:

echo word1 word2 word3 word2 <END> word2 | ./word_counter_app 

cat test_case_1 | ./word_couner_app 

./word_couner_app < ./test_cast_2 

那种调用的足够有用的,它是最好避免尝试读取后的EOF即使你不关心可移植性。

0

cin将在第一次循环后设置EOF。所以在你输入任何东西之前,你只需要清除它:

cin.clear(); 
cin >> UWord;