I'm trying to add all numbers from string, but I can't figure out how do I add a 2 digit number.
ex: ab32d3
I want the answer to be 35.
This is my code:
int main()
{
int max=0,min=100000,sum=0,totalsum=0;
string s;
ifstream in ("Unos.txt");
while(getline(in,s))
{
cout<<s<<endl;
for(int i=0;i<s.length();++i)
{
if(s[i]>max)
{
max=s[i]-'0';
}
if(s[i]<min)
{
min=s[i]-'0';
}
if(isdigit(s[i]))
{
sum=10*sum+s[i]-'0';
}
else
{
totalsum+=sum;
sum=0;
}
}
}
totalsum+=sum;
cout<<"Najveci broj je: "<<max<<endl;
cout<<"Najmanji broj je: "<<min<<endl;
cout<<"Zbir svih brojeva je: "<<totalsum<<endl;
return 0;
}
Try this:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string str = "ab32d3", temp;
int sum = 0;
for ( int i = 0; i < str.size(); i++ ) {
if ( isdigit(str[i]) ) temp.push_back(str[i]);
else {
if ( temp.size() > 0 ) {
sum += stoi(temp);
temp = string();
}
}
}
// Last number (if exists)
if ( temp.size() > 0 ) sum += stoi(temp);
cout << sum << endl;
return 0;
}
It will print 35
#include <iostream>
#include <cctype>
int main() {
std::string s = "ab32d3";
int value_so_far = 0;
int total = 0;
for (int i = 0; i < s.length(); ++i)
{
if (isdigit(s[i])) { // This keeps a running total until the number ends
value_so_far = 10 * value_so_far + s[i] - '0';
} else { // Here the number has ended - Add to the total and reset
total += value_so_far;
value_so_far = 0;
}
}
// Got to the end - Add what is left!
total += value_so_far;
std::cout << "Ans:" << total << std::endl;
// your code goes here
return 0;
}
Here is the link: ideone code.
Please check the comments in the code as to the explanation.
Related
Assume that the value of a = 1, b = 2, c = 3, ... , z = 26. You are given a numeric string S. Write a program to return the list of all possible codes that can be generated from the given string.
For most of the cases this code works but it gives wrong output for inputs which have numbers greater than 26. For eg: 12345.
#include <iostream>
#include <string.h>
using namespace std;
using namespace std;
int atoi(char a)
{
int i=a-'0';
return i;
}
char itoa(int i)
{
char c='a'+i-1;
return c;
}
int getCodes(string input, string output[10000]) {
if(input.size()==0)
{
return 1;
}
if(input.size()==1)
{
output[0]=output[0]+itoa(atoi(input[0]));
return 1;
}
string result1[10000],result2[10000];
int size2;
int size1=getCodes(input.substr(1),result1);
if(input.size()>1)
{
if(atoi(input[0])*10+atoi(input[1])>10&&atoi(input[0])*10+atoi(input[1])<27)
{
size2=getCodes(input.substr(2),result2);
}
}
for(int i=0;i<size1;i++)
{
output[i]=itoa(atoi(input[0]))+result1[i];
}
for(int i=0;i<size2;i++)
{
output[i+size1]=itoa(atoi(input[0])*10+atoi(input[1]))+result2[i];
}
return size1+size2;
}
int main(){
string input;
cin >> input;
string output[10000];
int count = getCodes(input, output);
for(int i = 0; i < count && i < 10000; i++)
cout << output[i] << endl;
return 0;
}
if i give input 12345, the output is:
"
abcde
awde
lcde
l"
instead of :
"
abcde
awde
lcde"
i got it fellow members. i did not initialised the size2 variable to zero. also i didn't use >= operator.
int getCodes(string input, string output[10000]) {
if(input.size()==0)
{
output[0]="";
return 1;
}
if(input.size()==1)
{
output[0]=itoa(atoi(input[0]));
return 1;
}
string result1[10000],result2[10000];
int size2=0;
int size1=getCodes(input.substr(1),result1);
if(input.size()>1)
{
if(atoi(input[0])*10+atoi(input[1])>=10&&atoi(input[0])*10+atoi(input[1])<27)
{
size2=getCodes(input.substr(2),result2);
}
}
int k=0;
for(int i=0;i<size1;i++)
{
output[k++]=itoa(atoi(input[0]))+result1[i];
}
for(int i=0;i<size2;i++)
{
output[k++]=itoa(atoi(input[0])*10+atoi(input[1]))+result2[i];
}
return k;
}
this is the final code for getCodes function. Thanks everyone :)
You can do that more simply with something like this:
#include <utility>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void getCodesRec(unsigned int num, string& current, vector<string>& result)
{
// First and last chars for the codes
static constexpr char FIRST_CHAR = 'a';
static constexpr char LAST_CHAR = 'z';
if (num == 0)
{
// When there is no more number add the code to the results
result.push_back(current);
}
else
{
// Add chars to the existing code
unsigned int next = num;
unsigned int rem = next % 10;
unsigned int f = 1;
// While we have not gone over the max char number
// (in practice this loop will run twice at most for a-z letters)
while (next > 0 && rem <= (unsigned int)(LAST_CHAR - FIRST_CHAR) + 1)
{
next = next / 10;
if (rem != 0) // 0 does not have a replacement
{
// Add the corresponding char
current.insert(0, 1, FIRST_CHAR + char(rem - 1));
// Recursive call
getCodesRec(next, current, result);
// Remove the char
current.erase(0, 1);
}
// Add another number
f *= 10;
rem += f * (next % 10);
}
}
}
vector<string> getCodes(unsigned int num)
{
vector<string> result;
string current;
getCodesRec(num, current, result);
return result;
}
int main()
{
unsigned int num = 12345;
vector<string> codes = getCodes(12345);
cout << "Codes for " << num << endl;
for (string& code : codes)
{
cout << "* " << code << endl;
}
return 0;
}
Output:
Codes for 12345
* abcde
* lcde
* awde
I am working on a brute force task, but when I run my program, it gives an empty output file. Can anybody please help me fix this? The problem statement is below along with my code after that.
PROBLEM STATEMENT:
Write a program that reads two numbers (expressed in base 10):
N (1 <= N <= 15)
S (0 < S < 10000)
and then finds and prints (in base 10) the first N numbers strictly greater than S that are palindromic when written in two or more number bases (2 <= base <= 10).
Solutions to this problem do not require manipulating integers larger than the standard 32 bits.
CODE
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <fstream>
using namespace std;
string convert(int num, int base)
{
int quo = 100000;
int rem = 0;
string to_reverse;
while (quo > 0)
{
quo = num / base;
rem = num % base;
to_reverse += to_string(rem);
num /= base;
}
reverse(to_reverse.begin(), to_reverse.end());
return to_reverse;
}
bool is_pal(string conv_num)
{
string reversed_conv_num = conv_num;
reverse(reversed_conv_num.begin(), reversed_conv_num.end());
if (reversed_conv_num == conv_num)
{
return true;
}
return false;
}
int main()
{
ofstream fout("dualpal.out");
ifstream fin("dualpal.in");
int n, start;
fin >> n >> start;
vector<int> finals;
int times = 0;
for (int i = start + 1; i <= 10000; i++)
{
if (times == n)
{
for (auto x : finals)
{
fout << x << "\n";
}
break;
}
else
{
for (int j = 2; j <= 10; j++)
{
if(is_pal(convert(i, j)) == true)
{
times++;
finals.push_back(i);
}
}
}
}
return 0;
}
Try this code. I made some changes.
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <fstream>
using namespace std;
string convert(int num, int base)
{
int quo = 100000;
int rem = 0;
string to_reverse;
ostringstream str1; /*this and the next commented lines are added because "to_string" didnt work in my compiler*/
while (quo > 0)
{
quo = num / base;
rem = num % base;
str1 << rem; //this
to_reverse += str1.str(); //and this
num /= base;
}
reverse(to_reverse.begin(), to_reverse.end());
return to_reverse;
}
bool is_pal(string conv_num)
{
string reversed_conv_num = conv_num;
reverse(reversed_conv_num.begin(), reversed_conv_num.end());
if (reversed_conv_num == conv_num)
{
return true;
}
return false;
}
int main()
{
ofstream fout;
fout.open("dualpal.out", ios::out); //open the file in binary mode
//ifstream fin("dualpal.in");
int n, start;
cin >> n >> start;
vector<int> finals;
int times = 0;
for (int i = start + 1; i <= 10000; i++)
{
if (times == n)
{
//just a simple iterator for vector
for (vector<int>::iterator it = finals.begin(); it != finals.end(); ++it)
{
fout << *it << "\n";
}
break;
}
else
{
for (int j = 2; j <= 10; j++)
{
if(is_pal(convert(i, j)) == true)
{
times++;
finals.push_back(i);
}
}
}
}
fout.close(); //close the file
return 0;
}
USE OF STRING STREAMS
int number = 1000;
ostringstream s;
s << number;
string str = s.str();
This method can be used to convert number to strings.
This code requires <sstream> header file.
I am a C++ noob. I have a list of numbers that I put into a Vector. All numbers are 9 digit integers and are unique. I want to know what is the least amount of digits (starting from the right) that can be used to uniquily identify each number in the set. right now there are only 6 numbers, but the list could potentially grow into the thousands. I have posted my code thus far (not working.)
EDIT output is the following...
digit is 1
digit is 1
digit is 1
RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms
This is mostly a learning exercise. Please be generous and explicit with your comments and solutions.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main() {
//declare stream variable and load vector with values
ifstream myfile("mydata.txt");
vector<int> myVector;
int num;
while (myfile >> num) {
myVector.push_back(num);
}
//sort and squack if there is a duplicate.
std::sort(myVector.begin(), myVector.end());
for (int i = 0; i < (myVector.size() - 1); i++) {
if (myVector.at(i) == myVector.at(i + 1)) {
printf("There are duplicate student numbers in the file");
exit(EXIT_FAILURE);
}
}
//if it get here, then there are no duplicates of student numbers
vector<int> newv;
int k = 1;
bool numberFound = false;
bool myflag = false;
while (numberFound == false) {
//loop through original numbers list and add a digit to newv.
for (int j = 0; j < myVector.size(); ++j) {
newv.push_back(myVector.at(j) % (10^k));
}
sort(newv.begin(), newv.end());
for (int i = 0; i < (newv.size() - 1); i++) {
if (newv.at(i) == newv.at(i + 1)) {
//there is a duplicate for this digit. Set flag.
myflag = true;
}
if (myflag == false) {
numberFound = true;
cout << "digit is " << k << endl;
} else {
k++;
}
}
}
// for (int i = 0; i < myVector.size(); i++) {
// cout << "||" << myVector.at(i) << "||" << endl;
// }
//
// for (int i = 0; i < newv.size(); i++) {
// cout << "---" << newv.at(i) << "---" << endl;
// }
return 0;
}
Check the below code.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <math.h>
using namespace std;
int main() {
//declare stream variable and load vector with values
ifstream myfile("mydata.txt");
vector<int> myVector;
int num;
while (myfile >> num) {
myVector.push_back(num);
}
//sort and squack if there is a duplicate.
std::sort(myVector.begin(), myVector.end());
for (int i = 0; i < (myVector.size() - 1); i++) {
if (myVector.at(i) == myVector.at(i + 1)) {
printf("There are duplicate student numbers in the file");
exit(EXIT_FAILURE);
}
}
//if it get here, then there are no duplicates of student numbers
vector<int> newv;
int k = 1;
bool numberFound = false;
bool myflag = false;
int p = 1;
while (numberFound == false) {
//loop through original numbers list and add a digit to newv.
newv.clear();
p = p * 10;
for (int j = 0; j < myVector.size(); ++j) {
newv.push_back(myVector[j] % p);
}
sort(newv.begin(), newv.end());
myflag = false;
for (int i = 0; i < (newv.size() - 1); i++) {
if ( newv[i] == newv[i+1]) {
//there is a duplicate for this digit. Set flag.
myflag = true;
break;
}
}
if (myflag == true){
k ++;
}else{
numberFound = true;
cout << "digit is " << k << endl;
break;
}
}
return 0;
}
Sample Input:
123451789
123456687
125456789
123456780
Output:
digit is 4
I wrote simple binary calculator,which I'm going to develop.Everything works for a few first calculations,but after that the program chrashes-"Binary.exe has stopped working".I think there might be something wrong with dynamicly allocated array in function "decToBin()",but i can't spot the issue.Here's the code:
#include <iostream>
#include <math.h>
#include <string>
#include <conio.h>
using namespace std;
void binToDec()
{
string bin;
cout<<"Binary code: ";
cin>>bin;
int powr = 0;
int num = 0;
long long sum = 0;
for(int i=bin.size()-1; i>=0; i--)
{
if(bin[i] == '1')
{
num = 2;
}
else if(bin[i] == '0')
{
num = 0 ;
}
sum += pow(num,powr);
cout<<sum<<endl;
powr++;
}
cout<<"Decimal: "<<sum<<endl;
sum = 0;
powr = 0;
num = 0;
}
void decToBin()
{
int dec = 0;
cout<<"Decimal number or digit: ";
cin>>dec;
int i = 0;
int *numBin = new int[i];
while(dec > 0)
{
numBin[i] = dec%2;
dec = dec/2;
i++;
}
cout<<"Binary: ";
for(int j = i-1; j>=0; j--)
{
cout<<numBin[j];
}
cout<<"\n";
i = 0;
delete [] numBin;
}
int main()
{
//USER INPUT
int nav = 0;
while(true)
{
cout<<"\n";
cout << "1.Binary to decimal:"<<endl;
cout << "2.Decimal to binary:"<<endl;
cin>>nav;
switch(nav)
{
case 1:
{
binToDec();
break;
}
case 2:
{
decToBin();
break;
}
}
}
return 0;
}
Your problem:
int *numBin = new int[i]; //i is 0, then you add elements to it
An easy solution, use std::vector:
vector<int> numBin;
...
numBin.push_back(dec%2);
You don't have to worry about dynamic memory at all now.
Hey so I am trying to write a simple program that adds spaces to a given string that has none in C++ here is the code I have written:
#include <iostream>
#include <string>
using namespace std;
string AddSpaceToString (string input)
{
const int arrLength = 5;
int lastFind = 0;
string output;
string dictionary[arrLength] = {"hello", "hey", "whats", "up", "man"};
for (int i = 0; i < input.length(); i++)
{
for (int j = 0; j < arrLength; j++)
{
if(dictionary[j] == input.substr(lastFind, i))
{
lastFind = i;
output += dictionary[j] + " ";
}
}
}
return output;
}
int main ()
{
cout << AddSpaceToString("heywhatshelloman") << endl;
return 0;
}
For some reason the output only gives hey whats and then stops. What is going on I can't seem to make this very simple code work.
After reading "hey" and "whats", the value of i is more than the length of "hello" and hence no such substring exists for the code input.substr(lastFind, i).
You should check for the length of possible substring (dictionary[j]) and not i.
input.substr( lastFind, dictionary[j].size() )
Also you will have to change:
lastFind += dictionary[j].size();
So the if loop becomes:
if(dictionary[j] == input.substr(lastFind, dictionary[j].size() ))
{
lastFind += dictionary[j].size();
output += dictionary[j] + " ";
}
this works
#include <iostream>
#include <string>
using namespace std;
string AddSpaceToString (string input)
{
const int arrLength = 5;
unsigned int lastFind = 0;
string output;
string dictionary[arrLength] = {"hello", "hey", "whats", "up", "man"};
for (int j = 0; lastFind < input.size() && j < arrLength; ++j)
{
if(dictionary[j] == input.substr(lastFind, dictionary[j].size()))
{
lastFind += dictionary[j].size();
output += dictionary[j] + " ";
j = -1;
}
}
return output;
}
int main ()
{
cout << AddSpaceToString("heywhatshelloman") << endl;
return 0;
}