如何在 c++ 集中插入元素,直到按下 Enter 键

How to insert elements in a c++ set until enter is pressed?

本文关键字:Enter 元素 c++ 集中 插入      更新时间:2023-10-16

例如:如果给出 1,5,88,99,7 作为输入,则在一个集合中插入 1 5 88 99 7,然后按 Enter 键。我的代码:

#include <bits/stdc++.h>
using namespace std;
set <char> num;
set <char> ::iterator i;
int main()
{
 int a;
 while(a=getchar())
 {
    if(a!='n')
    {
        if(a!=',')
            num.insert(a);
    }
    else
        break;
}
for(i=num.begin(); i!=num.end(); i++)
    cout<<*i<<endl;
}

我得到的输出:15789

#include <set>
#include <string>
#include <sstream>
using namespace std;
int main() {
   // cin >> s;
   string s = "5,2,3,4,1",t = "";
   stringstream ss(s);
   set<int> s_;
   while( getline(ss,t,',') )
       s_.insert(stoi(t));
   for(auto i : s_)
       cout << i << " ";
}

输出: 1 2 3 4 5

1(为了匹配修改后的问题(读取任何长度的整数(字符,意味着您需要查看每个字符并查看它是否是数字。 如果是,则需要根据收到的每个附加数字保留一个运行值。

2(如果要保存实际的整数值,您的集合必须是int,而不是char。

#include <iostream>
#include <set>
using namespace std;
set <int> num;
set <int> ::iterator i;
int main()
{
  int a;
  int full_num=0;
  while(a=getchar())
  {
     if (isdigit(a)) 
     {
       full_num = full_num*10 + (a - '0');
     } 
       else if (a==',' || a=='n') 
     {
       num.insert(full_num);
       full_num = 0;
       if (a=='n') break;
     }
   }
   for(i=num.begin(); i!=num.end(); i++)
       cout<<*i<<endl;
 }