How to convert digit character to string using c++ - c++

This is my code:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string userInput;
std::getline(std::cin, userInput);
int sum;
int result;
std::string numDigit;
bool space = true;
for (int i = 0; i < userInput.length(); i++) {
if (isdigit(userInput[i]) && space) {
numDigit += userInput[i];
space = false;
}else if(isdigit(userInput[i]) && !space) {
numDigit += userInput[i];
}else if (!isdigit(userInput[i]) && !space) {
std::stringstream(numDigit) >> result;
sum += result;
numDigit = "";
result = 0;
space = true;
}
std::cout << sum;
}
}
If i input 1 2 3 with space, it should ouput sum = 6, but instead it output many digits of number why is it like that ? (sorry I'm beginner of c++)

You are using your variables sum and result without initializing them.
When you are using any compiler, you cannot assume that variables will be automatically initialized to zero. So, if you use an uninitialized variable, the behavior of your program will be undefined, it might be just nice the value you want, or it will be filled with garbage values like 80123901723012, -190283812791, etc...
int sum = 0;
int result = 0;
Declare a variable and initialize it to zero is always a good practice.
EDIT :
The problem your code have is:
1. you should only output sum after for loop end.
2. your should check for i <= userInput.length() instead of checking for less than only.
modified code:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string userInput;
std::getline(std::cin, userInput);
int sum = 0;
int result = 0;
std::string numDigit = "";
bool space = true;
for (int i = 0; i <= userInput.length(); i++) {
if (isdigit(userInput[i]) && space) {
numDigit += userInput[i];
space = false;
}
else if (isdigit(userInput[i]) && !space) {
numDigit += userInput[i];
}
else if (!isdigit(userInput[i]) && !space) {
std::stringstream(numDigit) >> result;
sum += result;
numDigit = "";
result = 0;
space = true;
}
}
std::cout << "sum = " << sum << std::endl;
}
Thanks for pointing out my mistake Pete, I've made the correction to my post.

Related

Why does a program crashing but being normal when debugging (using code blocks)

I am solving Contest Scoreboard (UVA(10258), PC(110207)), and wrote a C++ code like this:
#include <iostream>
#include <utility>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <cstdlib>
#include <algorithm>
//100 contestants, 9 problems.
//data need to store for each contestant: num of problem solved, time consumed.
//array of contestants' data should be sorted by those two values. <- vector of pairs
//problem solved <- set
//time consumed <- check for contestant and L for each line and add them up.
std::vector< std::pair<int, std::pair<int, int> > > contestants;
std::vector<std::set<int>> problem_solved; //store contestants' solved problems
void add_entry(std::string line)
{
int begin = 0;
int end = line.find(" ", begin);
int contestant = std::atoi(line.substr(0, end - begin).c_str());
begin = end + 1;
end = line.find(" ", begin);
int problem = atoi(line.substr(begin, end - begin).c_str());
begin = end + 1;
end = line.find(" ", begin);
int time = atoi(line.substr(begin, end - begin).c_str());
char status = line.back();
switch (status)
{
case 'C':
{
if (!problem_solved[contestant].count(problem))
{
problem_solved[contestant].insert(problem);
}
break;
}
case 'I':
time = 20;
break;
default:
time = 0;
break;
}
contestants[contestant].first = contestant;
contestants[contestant].second.second += time;
}
bool comp(std::pair<int, std::pair<int, int>> a, std::pair<int, std::pair<int, int>> b)
{
if (a.second.first == b.second.first)
{
return (a.second.second <= b.second.second);
}
else
{
return (a.second.first > b.second.first);
}
}
void calc_results()
{
for (int i = 0; i < 100; i++)
{
contestants[i].second.first = problem_solved[i].size();
}
std::sort(contestants.begin(), contestants.end(), comp);
}
int main()
{
//initialize it so that contestants with no records can be ruled out
for (int i = 0; i < 100; i++)
{
contestants.push_back(std::make_pair(0, std::make_pair(0, 0)));
}
//initialization
for (int i = 0; i < 100; i++)
{
problem_solved.push_back(std::set<int>{});
}
std::string line_1;
int num_case;
std::getline(std::cin, line_1);
//get number of cases
num_case = atoi(line_1.c_str());
//get one blank line
std::string blank;
std::getline(std::cin, blank);
//get num_case 's cases.
int i = 0;
std::string line_2;
while (i < num_case)
{
//get unknown number of entries
std::getline(std::cin, line_2);
//move to next case
if (line_2.empty())
{
i++;
}
else
{
//handle one line of entry
add_entry(line_2);
}
}
//calculate final results
calc_results();
//print results
for (int i = 0; i < 100; i++)
{
std::cout << i << "\n";
if (contestants[i].second.first == 0)
{
continue;
}
else
{
std::cout << contestants[i].first << " " << contestants[i].second.first << " " << contestants[i].second.second << "\n";
}
}
return 0;
}
When I run debug, it behaves normally:
1 2 66
3 1 11
But when I run the executable directly, the output is like:
some large integers some large integers some large integers
1 2 66
3 1 11
Then the program crashed, showing "Process returned -1073741819".
I suspect that it is some kind of memory leak, but can't understand what happened. Could anyone give me some help? Thanks!

Run length encoding in C++

#include <iostream>
#include <string>
#include <vector>
using namespace std;
string compression(const string & str){
int i = str.size();
string letters;
letters[0] = str[0];
for (int j = 0; j < i; ++j){
int count = 1;
while (str[j] == str[j+1]){
count++;
j++;
}
letters.push_back('0' + count);
letters.push_back(str[j]);
}
return letters;
}
int main(){
string input;
char c;
try {
cout << "Enter the data to be compressesed: "<< endl;
cin >> input;
for (int z = 0; z < input.length(); ++z){
c = input.at(z);
}
if (!(c >= 'a' && c <= 'z')){
throw runtime_error("error: invalid input");
}
}
catch (runtime_error& excpt){
cout << excpt.what() <<endl;
return 0;
}
cout << "The compressed data is " << compression(input) << endl;
return 0;
}
The expected output is , repeated for each run of characters. Here is the amount of times is repeated in sequence.
Some examples:
aaeeeeae = 2a4e1a1e
rr44errre = invalid input
eeeeeeeeeeeeeeeeeeeee = 21e
the code works properly only if the character is repeated consecutively 9 times or less. for values of 10 and more the input is other symbols.
For example it stays blank for 10, so if input is 'aaaaaaaaaabb',output just would be 'a2b' instead of '10a2b'. For 11 its outputs ';',
so if input is 'aaaaaaaaaaabb', output is ';a2b' for some reason.
So my question is, how do i make the pushback work for all numbers and not just from 0-9?
Thank you for your time if u've gotten to here. ^^
If you can use c++11 or newer your function compression could look like:
string compression(const string & str){
int i = str.size();
string letters;
for (int j = 0; j < i; ++j){
int count = 1;
while (str[j] == str[j+1]){
count++;
j++;
}
letters += std::to_string(count);
letters.push_back(str[j]);
}
return letters;
}

empty output on brute force task

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.

Adding all numbers from string

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.

least number of digits without duplicates

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