Can't convert string to int c++ [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm making a simple number reverse program and I've tried many different ways to convert the string to an int but all I get is errors or "core dumped" while executing or compiling. I'm new to C++.
#include <bits/stdc++.h>
using namespace std;
void solve(){
string n, ans="";
cin >> n;
for(int i=0; i<n.length()+1;++i){
ans += n[n.length()-i];
}
int num = stoi(ans);
cout << ans << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >>t;
while(t--){
solve();
}
return 0;
}

Your for loop is accessing an out-of-bounds element of the n string on its first iteration: when i is zero, you are attempting to access the n.length() element of n but the last element is at position n.length() - 1. Remember that arrays, strings and other 'containers' in C++ start at element 0 and end at element n-1 – where n is the size (length) of the container.
You can fix this by starting your loop with i = 1 rather than with i = 0.
#include <iostream>
#include <string>
using std::string;
using std::cout, std::cin; // Pre C++17, you'll need 2 separate "using" statements.
void solve()
{
string n, ans = "";
cin >> n;
for (size_t i = 1; i <= n.length(); ++i) {
ans += n[n.length() - i];
}
int num = stoi(ans);
cout << num << "\n"; // I've changed to print "num" rather than "ans"
}
int main()
{
// For someone who is "new to C++," the following two lines are probably overkill...
// std::ios::sync_with_stdio(false);
// cin.tie(NULL);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
Also please read Why should I not #include <bits/stdc++.h>? and Why is "using namespace std;" considered bad practice?
On the issue I've commented as "overkill," see: Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); (especially the top/accepted answer).

Related

Segfault when puting cin value into array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Here is all of my code:
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
#include <iostream>
using namespace std;
int main(){
ifstream fin("cereal.in");
ofstream fout("cereal.out");
int n, m, f, s;
cin >> n >> m;
int c1[n];
int c2[n];
for(int i = 0; i < n; i++){
cin >> c1[i] >> c2[i];
c1[i]--;
c2[i]--;
}
vector<int> fm(m, -1);
set<int> fs;
vector<int> ans;
for(int i = n-1; i >= 0; i++){
if(fs.find(c1[i]) == fs.end()){
fs.insert(c1[i]);
}else{
if(fs.find(fm[c1[i]]) == fs.end()){
fs.insert(fm[c1[i]]);
}
}
fm[c1[i]] = c2[i];
ans.push_back(fs.size());
}
for(int i = 0; i < n; i++){
cout << ans[i] << endl;
}
}
In the first for loop when i = n-1, I'm getting a Segmentation fault: 11. I used a cout call after the cin in that for loop to find this information.
What is the reason for this? It was working fine a couple of minutes ago and I didn't even touch this part of the code and it stopped working. I'm using VS Code, but even when I use an online compiler it doesn't work. Here is the input I am giving:
4 2
1 2
1 2
1 2
1 2
Please help me. This isn't the first time I'm having a problem like this.
for(int i = n-1; i >= 0; i++){ // <------
if(fs.find(c1[i]) == fs.end()){
fs.insert(c1[i]);
}else{
if(fs.find(fm[c1[i]]) == fs.end()){
fs.insert(fm[c1[i]]);
}
}
fm[c1[i]] = c2[i];
ans.push_back(fs.size());
}
Change to i--. You're accessing c1[i] with out of bound index.
You have an array index out-of-bounds bug, causing the program to access data where it shouldn't.
for(int i = n-1; i >= 0; i++){
In the above statement the integer i wraps around until it overflows, thus indexing c1 into forbidden regions of memory.
The OS is alerted of the memory violation and killed the misbehaving program. When this happens the program is said to encounter a segmentation fault.

How does change in Passing parameters changes the output of the Code? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
When I pass only Sum as Parameter in My coin Exchange Problem to find no of ways to find the amount Sum..
Example
if the coins are {2,3,5} and the desired sum is 9 i get correct output as 8.
This code :
#include <bits/stdc++.h>
using namespace std;
int n, sum, a[105];
int fun(int sum) {
int S = 0;
if(sum == 0) return 1;
if(sum < 0) return 0;
for(int i=1;i<=n;i++) {
S += fun(sum - a[i]);
}
return S;
}
int main()
{
cin >> n;
cin >> sum;
for(int i=1;i<=n;i++ ) {
cin >> a[i];
}
cout << fun(sum);
return 0;
}
But when I also give Current Index as a parameter it gives me output as 3 which is wrong.
This code :
#include <bits/stdc++.h>
using namespace std;
int n, sum, a[105];
int fun(int sum, int idx) {
int S = 0;
if(sum == 0) return 1;
if(idx > n) return 0;
if(sum < 0) return 0;
for(int i=idx;i<=n;i++) {
S += fun(sum - a[i], i);
}
return S;
}
int main()
{
cin >> n;
cin >> sum;
for(int i=1;i<=n;i++ ) {
cin >> a[i];
}
cout << fun(sum,1);
return 0;
}
But WHY??
Is my parameter passing in this case is wrong?
You don't have the same result between your 2 solutions because in the first, at each "function call", you will iterate from 1 to N and in your second solution, you will iterate from Index to N. So the number of loop will be different.

What's wrong with my code about find the max one and the min one by vector [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I wrote a code,it will find the max one and min one in an arr by vector
but I simply don't know what I've made an error.
Every time I try it return zero for me.lol
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int a[999];
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
vector<int> arr(a[1], a[n]);
int max = *max_element(arr.begin(), arr.end());
int min = *min_element(arr.begin(), arr.end());
int dis = max - min; cout << dis << endl;
return 0;
}
What's wrong with my code [?]
Honestly, almost everything.
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
using namespace std; can cause harm, not in small examples like this, but better don't get used to bad habits.
int main()
{
int a[999];
You allocate space for 999 elements. What if the user enters 1000 for n ?
int n;
cin >> n;
Array indices start at 0 not at 1. Lets say the user enters 999 then you are still going out of bounds invoking undefined behaviour because a[999] is not an element of the array.
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
You are calling the std::vector constructor that sizes the vector to hold a[1] elements with value a[n]. This is not copying the elements from the array to the vector! All elements will have the same value, hence you always get 0 as the result.
vector<int> arr(a[1], a[n]);
int max = *max_element(arr.begin(), arr.end());
int min = *min_element(arr.begin(), arr.end());
This is not really wrong, but written unnecessarily complicated. max_element returns an iterator and you can use eg. std::distance to get the distance between two iterators.
int dis = max - min; cout << dis << endl;
return 0;
}
You could write it like this
#include<iostream>
#include<algorithm>
#include<vector>
int main()
{
std::vector<int> x;
int n;
std::cin >> n;
x.resize(n);
for (auto& e : x) std::cin >> e;
auto max = std::max_element(x.begin(), x.end());
auto min = std::min_element(x.begin(), x.end());
std::cout << std::distance(max,min) << "\n";
return 0;
}
Live Demo
PS: Be careful with std::distance. Prior to C++11 it was undefined behaviour to call it with a second argument that cannot be reached from the first iterator passed by going forward. Also note that there is std::minmax_element that will give you both iterators from only traversing the vector once.

I have to calculate difference of sum of diagonal elements of a square matrix [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
In the following program:
#include <iostream>
#include <cmath>
using namespace std;
int diagonalDifference(int x[][],int n)
{
int sum1=0,sum2=0,y;
for(int i=0;i<n;i++)
{
sum1+=x[i][i];
sum2+=x[i][n-1-i];
}
y=abs(sum1-sum2);
return y;
}
int main()
{
int n,**z;
cin>>n;
int arr[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>arr[i][j];
}
}
z=diagonalDifference(arr,n);
cout<<x;
return 0;
}
I get a compilation error I don't understand.
error:declaration of 'x' as multidimensional array must have bounds for all dimensions except the first
Could you help me fix it?
int[][] is not a valid type:
int diagonalDifference(int x[][],int n)
You declare z as an int**:
int n,**z;
But you assign it an int:
int diagonalDifference(int x[][],int n);
z=diagonalDifference(arr,n);
And finally you print x which does not exist:
cout<<x;
As rules of thumb:
declare only one variable per line, and give it a meaningful name;
declare what possibly can as const;
Don't use C-style arrays unless you have to; prefer std::vector for instance;
don't use using namespace std;
much more you need to learn.
.
int diagonalDifference(int x**,int n) { /* .... */ }
int matrix_size = 0;
std::cin >> matrix_size;
std::vector<std::vector<int>> matrix{matrix_size, std::vector<int>{matrix_size}};
/* fill the matrix */
const int diag_diff = diagonalDifference(matrix, matrix_size);
std::cout << diag_diff << '\n';

Deal with segmentation fault [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to solve a CodeChef problem. Whenever I run it I get a segmentation fault. This is the link to the problem: Malvika is peculiar about color of balloons
Here is my code :
#include<iostream>
#include<cstring>
#include<algorithm>
int main(){
std::string balloonColors;
size_t numberOfAmber;
size_t numberOfBrass;
int t;
int results[t];
std::cin >> t;
for (int i = 0; i < t; i++){
int result = 0;
std::cin >> balloonColors;
numberOfAmber = std::count(balloonColors.begin(), balloonColors.end(), 'a');
numberOfBrass = std::count(balloonColors.begin(), balloonColors.end(), 'b');
if (numberOfAmber == 0 || numberOfBrass == 0){
result = 0;
}
if (numberOfAmber <= numberOfBrass){
result = (int)numberOfAmber;
}
else {
result = (int)numberOfBrass;
}
results[i] = result;
}
for (int x = 0; x < t; x++){
std::cout << results[x] << std::endl;
}
}
These lines is the problem:
int t;
int results[t];
You declare results using the uninitialized variable t. An uninitialized variable have an indeterminate value, and using it before initialization leads to undefined behavior.
You should use a std::vector here, and set its size once you get the actual size from the user:
int t;
std::vector<int> results;
std::cin >> t;
results.resize(t);
Arrays in C++ need to have a fixed size. You defined results with size t, which isn't fixed.
To use dynamic size, use a std::vector instead:
#include <vector>
...
int t;
std::cin >> t;
std::vector<int> results (t);