How can I enter an integer value a using cin and put it in vector<int>in
until a new line occurs?
I'm not sure if "Let me enter the integer value a until a new line occurs" goes down, but if you mean to enter multiple numbers separated by spaces between the first new line, how about this?
#include<iostream>
# include <sstream>
# include <vector>
# include <iterator>
# include <algorithm>
int main()
{
std::vector<int>in;
std::string line;
if(std::getline(std::cin,line)){
std::istringstream s(line);
std::copy(std::istream_iterator<int>(ss), std::istream_iterator<int>(), std::back_inter(in));
}
// Show what you have been entered
std::copy(in.begin(), in.end(), std::ostream_iterator<int>(std::cout, ""));
}
Or, if you really want to use variable a,
#include<iostream>
# include <sstream>
# include <vector>
# include <iterator>
# include <algorithm>
int main()
{
std::vector<int>in;
std::string line;
if(std::getline(std::cin,line)){
std::istringstream s(line);
inta;
while(ss>>a){
in.push_back(a);
}
}
// Show what you have been entered
std::copy(in.begin(), in.end(), std::ostream_iterator<int>(std::cout, ""));
}
How about this?
#include<locale>
# include <iostream>
# include <sstream>
# include <vector>
structure word_separator:std::cttype<char>{
word_separator():std::cttype<char>(get_table()){}
static mask const*get_table(){
static mask rc [table_size];
rc['] = std::ctype_base::space;
rc['\n'] = std::cttype_base::space;
return&rc[0];
}
};
int
main(){
std::cin.imbue(std::locale(std::cin.getloc(), newword_separator)));
std::string word;
std::vector<int>in;
inta;
while(std::cin>>word){
std::istringstream s(word);
ss>>a;
if(ss.fail()){
std::cerr<<"invalid token:"<word<<std::endl;
} else{
in.push_back(a);
}
}
}
© 2024 OneMinuteCode. All rights reserved.