C++如何循环输入不定长度的字符串,并且遇到和之前输入的字符串重复的字符串后停下,然后将所有的字符串放入文件 shuchu.txt

C++如何循环输入不定长度的字符串,并且遇到和之前输入的字符串重复的字符串后停下,然后将所有的字符串放入文件 shuchu.txt

我这里用了unordered_set,因为它唯一可以用来判断当前输入的字符串是否与之前输入的字符串重复,在设置一个变量存储当前输入的字符串并写入到文件中


#include <iostream>
#include <fstream>
#include <unordered_set>
#include <string>

int main() {
    std::unordered_set<std::string> strings; 
    std::string input; 

    std::ofstream output_file("shuchu.txt"); 

    while (std::cin >> input) { 
        if (strings.count(input)) {
            break; 
        }
        strings.insert(input); 
        output_file << input << std::endl;
    }

    output_file.close(); 
    return 0;
}


#include <iostream>
#include <fstream>
#include <set>
#include <string>

using namespace std;

int main()
{
    set<string> s; // 使用 set 存储已经输入过的字符串

    string str;
    ofstream outfile("shuchu.txt"); // 打开输出文件

    while (cin >> str) // 循环输入字符串
    {
        if (s.count(str) > 0) // 如果输入的字符串已经在 set 中出现过,退出循环
            break;

        s.insert(str); // 将输入的字符串插入 set 中
        outfile << str << endl; // 将输入的字符串写入输出文件
    }

    outfile.close(); // 关闭输出文件

    return 0;
}