C++ 计数冗余字符串

c++ count redundant string

本文关键字:字符串 冗余 C++      更新时间:2023-10-16
#include <iostream>
#include <vector>
#include <string>
using std::cout; using std::endl;
using std::cin; using std::vector; using std::string;
int main()
{
    cout << "Input strings(end-of-file to exit):"<<endl;
    vector<string> strings;
    string x;

    while (cin >> x)
    {
        strings.push_back(x);
    }
    typedef vector<string>::size_type vc_sz;
    vc_sz size = strings.size();
    int same_string=0;
    for (int i = 0; i < size; i++)
    {
        for (int j = i+1; j < size; j++)
        {
            if (strings[i] == strings[j])
                ++same_string;
        }
    }
    cout << "Same string number:" << same_string << endl;
    system("pause");
    return 0;
}

这是一个简单程序的代码,用于计算有多少字符串输入是冗余的。一切似乎都很好,除了我需要输入两次文件末尾(ctr+z(才能结束循环并获得结果。我不知道为什么会发生这种情况。

您似乎正在尝试在行序列的末尾输出 EOF 字符:

> This is my inputEOF

这将迫使您输入另一个EOF以实际结束流。 如果要使用单个 EOF 结束流,则需要先按回车键:

> This is my inputENTER
> EOF

如果使用std::set,则可以显著简化代码

int main()
{
    cout << "Input strings(end-of-file to exit):"<<endl;
    set<string> strings;
    string x;
    int same_string=0;
    while (cin >> x)
    {
        if( !strings.insert(x).second ) ++same_string;
    }
    cout << "Same string number:" << same_string << endl;
    system("pause");
    return 0;
}