I need a string taken as input from the keyboard for example A 2 D F 5 A , it always has 6 total characters, How do I find the last int , in this case 5 and store it in a variable? I cant find anything anywhere.
From the internet I found some code that half works
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
struct not_digit {
bool operator()(const char c) {
return c != ' ' && !std::isdigit(c);
}
};
int main() {
int last;
std::string Serial(" 1 S 4 W 2 A");
not_digit not_a_digit;
std::string::iterator end = std::remove_if(Serial.begin(), Serial.end(), not_a_digit);
std::string all_numbers(Serial.begin(), end);
std::stringstream ss(all_numbers);
std::vector<int> numbers;
for(int i = 0; ss >> i; ) {
numbers.push_back(i);
last = i;
}
cout << last << endl;
return 0;
}
but I dont know how to take "Serial" from keyboard as doing so always results in the last number being 0 for some reason, so instead of 2 i get 0.
This would do:
Reverse the string.
Then find a digit in the string.
Notice the input string may not have digits.
[Demo]
#include <algorithm> // find_if
#include <cctype> // isdigit
#include <fmt/core.h>
#include <ranges>
int main() {
std::string str(" 1 S 4 W 2 A");
auto rev{ str | std::views::reverse };
auto it{ std::ranges::find_if(rev, [](unsigned char c) { return std::isdigit(c); }) };
if (it != std::cend(rev)) {
fmt::print("Last int found: {}\n", *it);
} else {
fmt::print("No int found.\n");
}
}
// Outputs:
//
// Last int found: 2
Also:
Walking the string backwards.
And stopping once you find a digit.
[Demo]
#include <cctype> // isdigit
#include <fmt/core.h>
int main() {
std::string str(" 1 S 4 W 2 A");
auto it{ std::crbegin(str) };
for (; it != crend(str); ++it) {
if (std::isdigit(*it)) {
fmt::print("Last int found: {}\n", *it - '0');
break;
}
}
if (it == crend(str)) {
fmt::print("No int found.\n");
}
}
Related
I want to take an integer and turn it into an array and then store it into a string in C++. But I do not know how to turn an integer into an array and then store it into a string. I am still learning C++, so help me, please. That's how I want it to be done:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int number = 3215;
//store the number into vector
vector<int> numbers;
//vector[0]=3
//vector[1]=2
//vector[2]=1
//vector[5]=5
//and then store it into string
string str;
//like this
//str=3215
return 0;
}
Please help me and show the code as well with explanation
Edit: I have some data to work with integer values with every digit which I can solve my own but for that, I need to first turn the integer into vector and return it as a string. THat's why I want to know how to turn integer into vector first and the that vector into string
Here you are:
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <algorithm>
#include <iterator>
int main() {
int n;
std::cin >> n;
std::vector<int> split(static_cast<int>(std::log10(n)) + 1);
auto royal_10 = split.rbegin();
auto cpy{ n };
do {
*royal_10++ = cpy % 10;
} while ((cpy /= 10) != 0);
std::string ret;
ret.reserve(split.size());
std::transform(split.cbegin(), split.cend(), std::back_inserter(ret),
[](int const dig) { return dig + '0'; });
return 0;
}
The easiest is : std::to_string(yourNum);
If you do need the steps:
std::vector<int> res;
int num;
std::cin >> num;
while(num>0)
{
res.insert(res.begin(),num%10);
num/=10;
}
and then
std::stringstream result;
std::copy(res.begin(), res.end(), std::ostream_iterator<int>(result, ""));
Since you insist on placing the integers in a vector first and then converting them to string later (when needed?), this can be a solution:
#include <iostream>
#include <string>
#include <vector>
int main( )
{
std::string number;
std::cin >> number;
std::vector<int> numbers;
numbers.reserve( number.length( ) );
for ( const auto digit : number )
{
numbers.push_back( digit - '0' );
}
std::cout << "\nElements of vector: ";
for ( const auto digit : numbers )
{
std::cout << digit << ' ';
}
std::cout << "\nElements of vector converted to `std::string`: ";
for ( const auto num : numbers )
{
std::string num_str { std::to_string( num ) };
std::cout << num_str << ' ';
}
std::cout << '\n';
}
Sample I/O:
1234
Elements of vector: 1 2 3 4
Elements of vector converted to `std::string`: 1 2 3 4
You are asking for a set of conversion functions, probably something like the code below. The ASCII codes of the digits are in sequential order, therefore transforming a digit character to a digit means subtracting '0' from it.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cassert>
std::vector<int> convert(const std::string& s)
{
std::vector<int> r;
std::transform(s.begin(), s.end(), std::back_inserter(r), [](auto e) {return e - '0'; });
return r;
}
std::string convert(const std::vector<int>& v)
{
std::string r;
std::transform(v.begin(), v.end(), std::back_inserter(r), [](auto e) {return e + '0'; });
return r;
}
std::vector<int> convert(const int n)
{
return convert(std::to_string(n));
}
int main()
{
auto v = convert(3215);
auto s = convert(v);
assert(s == "3215");
}
1)vector in c++ has vector object.push_back(); // which push data(any type) to vector array
2) using an iterator function you can retrieve that data and by dereferencing(*i)
you can receive that data in original form (which you had pushed)
3) use stringstream class or to_string() method to convert into string
//code
`
#include<vector>
#include<iostream>
int main()
{
int number=1234;
string str;
vector <int> obj;
obj.push_back(number);
for(auto i= obj.begin(); i!= obj.end();i++)
{
str = to_string((*i));
cout << end << str;
}
}
`
i know my question can be stupid for somebody, but i googled all day and try make my own solution but i failed.. Please help..
I need print all uniqe string from an simple array of strings.
example:
input: "Hi" "my" "name" "Hi" "potato" "text" "name" "Hi"
output: "my" "potato" "text"
I make just function to print everything once ("Hi", "my", "name", "potato", "text"), but i need ignore everything what is 2x and more times in array.
My algorythm was:
1. sort by bubblesort
print only last string from sorted sequence by using basic for and if
.. if(array[i]!=array[i+1]) //make something...
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<std::string> v = {
"Hi", "my", "name", "Hi", "potato", "text", "name", "Hi",
};
sort(v.begin(), v.end());
for (auto a = v.begin(), b = a; a != v.end(); a = b) {
b = find_if(b, v.end(), [&](string s) {return *b != s;});
if (distance(a, b) == 1)
cout << *a << '\n';
}
}
update : i was misunderstanding the question now it works as output in the question
simply you can count the occurrences of every string and print only strings which occur ones..
time complexity : O(N^2)
here is the code
#include<iostream>
#include<set>
#include <string>
#include <vector>
using namespace std;
int main()
{
int n; // number of strings you want in your array
cin >> n;
string t; // get t and push back it in the vector
vector <string> words; //we use vector to store as we will push back them
for(size_t i = 1;i <= n;i++)
{
cin >> t;
words.push_back(t);
}
for(int i = 0;i < words.size();i++)
{
int cnt = 0;
for(int j = 0;j < words.size() && cnt < 2;j++)
{
if(words[i] == words[j])
cnt++;
}
if(cnt == 1) //its unique..print it
cout << words[i] <<endl;
}
}
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> words{"Hi", "my", "name", "Hi", "potato", "text", "name", "Hi"};
std::sort(words.begin(), words.end());
for (auto curr = words.begin(); curr != words.end(); ) {
// If working w/ few duplicate words:
auto next = std::find_if(
curr + 1, words.end(), [&](const auto& s) { return s != *curr; }
);
/* If working w/ many duplicate words:
auto next = std::upper_bound(curr + 1, words.end(), *curr); */
if (std::distance(curr, next) == 1) {
std::cout << *curr++ << '\n';
} else {
curr = next;
}
}
}
Demo
std::sort, std::upper_bound, std::find_if, std::distance
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> words{"Hi", "my", "name", "Hi", "potato", "text", "name", "Hi"};
std::vector<std::string> out;
std::sort(words.begin(), words.end());
std::unique_copy(words.begin(), words.end(), std::back_inserter(out));
std::set_difference(words.begin(), words.end(), out.begin(), out.end(), std::ostream_iterator<std::string>(std::cout, " "));
}
Note: Not tested as I am writing this on my phone and in bed.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i,j;
string ss;
cin>>ss;
for(i=0;i<ss.length();i++)
{
for(j=1;j<ss.length();j++)
{
if(ss[i]==ss[j]&&i!=j)
{
ss[i]=' ';
}
}
}
for(i=0;i<ss.length();i++)
{
if(ss[i]!=' ')cout<<ss[i]<<" "; /// for unique element print
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n],i,j,k;
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n;i++)
{
for(j=1;j<n;j++)
{
if(a[i]==a[j]&&i!=j)
{
a[i]=0;
}
}
}
for(i=0;i<n;i++)
{
if(a[i]!=0)cout<<a[i]<<" ";
}
}
I am trying to write a program hat removes the character 'p' in Pineapple to output the word Pineale. Here is my current code. I found similar problems to this and thought this code would work but it is not unfortunately. Any help is appreciated!
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <limits>
using namespace std;
int main(){
remove(c,s);
}
string remove(char c, const string & s){
string s = "Pineapple";
char chars[] = "p";
for (unsigned int i = 0; i < strlen(chars); ++i)
{
s.erase(remove(s.begin(), s.end(), chars[i]), s.end());
}
cout << s << endl;
return s;
}
First, you did not define any c or s variables.
Second, your parameter in remove function is const, that means s is unchangeable.
The code below works in my VS2013.
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <limits>
using namespace std;
string remove(char* charToRemove, string &str){
//string s = "Pineapple";
//char chars[] = "p";
for (unsigned int i = 0; i < strlen(charToRemove); ++i)
{
str.erase(remove(str.begin(), str.end(), charToRemove[i]), str.end());
}
cout << str << endl;
return str;
}
int _tmain(int argc, _TCHAR* argv[])
{
string str("Pineapple");
char chars[] = "p";
remove(chars, str);
int i;
cin >>i;
}
Simply get the position of first 'p' from "Pineapple" using string::find(), then use string::erase(). No need to put string::erase() inside the loop.
string remove(char to_rem, string s) {
size_t pos = s.find( to_rem );
s.erase(pos, count(s.begin(), s.end(), to_rem) );
return s;
}
Modified code:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
string remove(char to_rem, string s) {
size_t pos = s.find( to_rem );
s.erase(pos, count(s.begin(), s.end(), to_rem) );
return s;
}
int main() {
cout << remove('p', "Pineapple");
}
Output:
Pineale
Try this:
struct slash_pred
{
char last_char;
slash_pred()
: last_char( '\0' ) // or whatever as long as it's not '/'
{
}
bool operator()(char ch)
{
bool remove = (ch == '/') && (last_char == '/');
last_char = ch;
}
};
path.erase( std::remove_if( path.begin(), path.end(),
slash_pred() ), path.end() );
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
I was recently doing a problem on string and suddenly this thing came to my mind that, how could i arrange the words of string in increasing order of their ascii values.
for example there's a string:
ab nn ac mm
so the output should be:
ab ac mm nn
actually i want to arrange them according to sum of ascii values of each letter of a word.
like in above example
ab has a sum of (97+98)=195
ac has a sum of (97+99)=196
and so on...
I want to know is there any efficient method of doing it or is there any function in STL which i can use here?
to make the question more clear Here's a second example if a string is-
acd abz
then output is-
acd abz
as sum of ascii of each letter of "acd" is lesser than that of "abz"
acd sums to (97+99+100)=296
abz sums to (97+98+122)=317
For your custom comparison, this code should do it, using a custom comparison function object (functor), i.e. in this case an object that implements bool operator(x,y) for usage in std::sort:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
struct str_comp
{
bool operator()(const std::string &lhs, const std::string &rhs) const
{
return std::accumulate(std::begin(lhs), std::end(lhs), 0) <
std::accumulate(std::begin(rhs), std::end(rhs), 0);
}
};
int main()
{
std::string input_str {"acd abz aaayyyyy zzzaaaaa"};
std::stringstream ss {input_str};
std::vector<std::string> v_str { std::istream_iterator<std::string>{ss}, {} };
std::sort(std::begin(v_str), std::end(v_str), str_comp());
for (const auto& elem : v_str)
std::cout << elem << std::endl;
}
Or, with a lambda function like a boss:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::string input_str {"acd abz aaayyyyy zzzaaaaa"};
std::stringstream ss {input_str};
std::vector<std::string> v_str { std::istream_iterator<std::string>{ss}, {} };
std::sort(std::begin(v_str), std::end(v_str),
[](const std::string& lhs, const std::string& rhs)
{
return std::accumulate(std::begin(lhs), std::end(lhs), 0) <
std::accumulate(std::begin(rhs), std::end(rhs), 0);
}
); // end std::sort
for (const auto& elem : v_str)
std::cout << elem << std::endl;
}
You can split the string and push_back in a vector and sort the vector in the following ways:
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
vector<string>v;
std::string s="ab nn ac mm";
istringstream t(s);
string ss;
while(t>>ss){
v.push_back(ss);
}
sort(v.begin(),v.end());
for (auto i=v.begin(); i!=v.end(); ++i){
cout<<*i<<endl;
}
return 0;
}
I assume your string has only one space, between a word and a word. Also I assume your string is trimed, which means it doesn't have any space in the head and tail of string. Let me show the code.
std::string sort_by_word_code(const std::string &src)
{
if (src.empty())
return "";
typedef std::string::const_iterator const_iterator;
typedef std::tuple<const_iterator, const_iterator, int> WordTuple;
std::vector<WordTuple> words;
const_iterator i = src.begin(), j;
int code;
while (1)
{
code = 0;
for (j = i; j != src.end() && *j != ' '; ++j)
{
code += *j;
}
words.push_back(WordTuple(i, j, code));
if (j == src.end())
break;
i = j + 1;
}
std::sort(words.begin(), words.end(),
[](const WordTuple &t1, const WordTuple &t2) { return std::get<2>(t1) < std::get<2>(t2); }
);
std::string result;
result.reserve(src.size());
for (auto it = words.begin(); ; )
{
result.insert(result.end(),
std::get<0>(*it),
std::get<1>(*it)
);
++it;
if (it == words.end())
break;
result.push_back(' ');
}
return result;
}
(live example)
The idea is simple. Create a vector which has the sum of ascii and begin/end of each word, sort it, and create a result string from it.
Well this code uses common standard functions/algorithms and is (in my opinion) efficient.
The splitting is done by a stringstream as you can see.
#include <algorithm>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main()
{
std::string input = "abz acd";
std::vector<std::string> substrings{ std::istream_iterator<std::string>{ std::stringstream{ input } }, std::istream_iterator<std::string>{} };
std::sort(std::begin(substrings), std::end(substrings),
[](const std::string& a, const std::string& b) -> bool
{
auto calcAscii = [](const std::string& str) -> int
{
int ascii = 0;
for (auto const& it : str)
{
ascii += static_cast<int>(it);
}
return ascii;
};
return calcAscii(a) < calcAscii(b);
});
std::string result;
for (auto const& it : substrings)
{
result += it + " ";
}
std::cout << result;
}
There is a string like this: M90I4D7
I need to push it in to this kind of struct:
struct CigarOp {
char Type; //!< CIGAR operation type (MIDNSHPX=)
uint32_t Length; //!< CIGAR operation length (number of bases)
//! constructor
CigarOp(const char type = '\0',
const uint32_t& length = 0)
: Type(type)
, Length(length)
{ }
};
which means I need to split it into 3 groups and each of them is a CigarOp( 'M' ,90 'I', 4 'D' ,7 )
Assuming that the string is of the form ([A-Z][0-9]+)*, you could quite simply do something like this:
#include <sstream>
...
std::vector<CigarOp> cigars;
std::istringstream parser("M90I4D7");
char c;
std::uint32_t l;
while(parser >> c >> l) {
cigars.push_back(CigarOp(c, l));
}
Note that this code doesn't do any sort of validation. If validation is necessary, one way to achieve it is to use Boost.Spirit (found on http://boost.org):
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted/struct.hpp>
#include <cstdint>
#include <iostream>
struct CigarOp {
char Type;
std::uint32_t Length;
};
BOOST_FUSION_ADAPT_STRUCT(CigarOp, (char, Type) (std::uint32_t, Length))
int main() {
using boost::spirit::qi::phrase_parse;
using boost::spirit::qi::char_;
using boost::spirit::qi::uint_;
using boost::spirit::qi::standard::space;
std::vector<CigarOp> cigars;
std::string s = "M90I4D7";
std::string::const_iterator first = s.begin(), last = s.end();
bool r = phrase_parse(first, last, *(char_ >> uint_), space, cigars);
if(r && first == last) {
// string was well-formed
for(auto const &cigar : cigars) {
std::cout << cigar.Type << ", " << cigar.Length << '\n';
}
}
}
how about:
#include <cstdio>
#include <cctype>
#include <vector>
#include <iostream>
#include <cstdlib>
using namespace std;
struct CigarOp {
char op; //!< CIGAR operation type (MIDNSHPX=)
int size; //!< CIGAR operation length (number of bases)
static int parse(const char* s,vector<CigarOp>& v)
{
char* p=(char*)(s);
while(*p!=0)
{
char* endptr;
CigarOp c;
c.op = *p;
if(!isalpha(c.op)) return -1;
++p;
if(!isdigit(*p)) return -1;
c.size =strtol(p,&endptr,10);
if(c.size<=0) return -1;
v.push_back(c);
p=endptr;
}
return 0;
}
};
int main(int argc,char** argv)
{
vector<CigarOp> cigar;
if(CigarOp::parse("M90I4D7",cigar)!=0) return -1;
for(size_t i=0;i< cigar.size();++i)
{
cout << cigar[i].op << ":" << cigar[i].size << endl;
}
return 0;
}
btw , for bioinformatics, you should ask biostars.org.