我似乎无法让 v.push.back() 处理字符串

I can't seem to get v.push.back() to work with strings

本文关键字:back 处理 字符串 push      更新时间:2023-10-16
// 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;
        }

}

    cout << "You word appeared " << count << " times" << endl;
    system("pause");
    return 0;
}

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

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

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

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

解决这个问题的典型方法是有一个"哨兵"词来表示这组词的结尾......例如:

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

您肯定希望在之后阅读Uword时使用if测试,这样您就可以识别并处理在没有看到<END>的情况下击中了EOF。

或者,让他们先输入Uword然后让循环读取所有单词,直到 EOF....

值得注意的是,对于某些共生者/环境,cin可以"体验"多个 EOF......例如,在 Windows CMD.EXE提示符下按 Control-Z 会生成 EOF,但如果调用 cin.clear() 重置 EOF 位,则可以在之后继续读取cin。 也就是说,如果您编写程序来依赖它,那么就无法使用以下语句自动调用/使用/测试它们:

echo word1 word2 word3 word2 <END> word2 | ./word_counter_app
cat test_case_1 | ./word_couner_app
./word_couner_app < ./test_cast_2

这种调用非常有用,即使您不关心可移植性,也最好避免尝试阅读 post-EOF。

cin将在第一次循环后设置EOF。因此,在输入其他任何内容之前,您只需要清除它:

cin.clear();
cin >> UWord;