Convert string to a vector of integers [closed] - c++

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 need to make a function in C++, which takes a string, which contains only digits, for example:
string s = "7654321"
and converts it to a vector of integers. So vector should be like this:
vec[1] = '7'
vec[2] = '6'
etc.
I tried to use isstringstream, but that was useless in this situation, cause that string has no spaces in it.

You can use a for loop to iterate through the string, and fill the vector with each value using push_back() and -'0'
assuming vector vec;
void fillVec(const string str1, vector<char> & vec) {
for(int i = 0; i < str1.length(); i++)
vec.push_back(str1[i]) - '0';
}
Example program implementing this
// Example program
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void fillVec(const string, vector<int> &);
int main()
{
vector<int> vec;
string str1 = "1234567";
fillVec(str1, vec);
for(int i = 0; i < vec.size(); i++)
cout << vec[i] << ", ";
return 0;
}
void fillVec(const string str1, vector<int> & vec) {
for(int i = 0; i < str1.length(); i++)
vec.push_back(str1[i]-'0');
}

Related

Filling vector with primes in a certain way [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
I was asked to fill a given vector with prime numbers, I can't use any other vectors, arrays or collections. I've come up with something like this, but it doesn't work properly and I can't figure out why.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool isPrime(int n){
if (n<=1){return false;}
for (int i = 2; i < n; i++){
if (n % i == 0){
return false;
}
}
return true;}
int fillWithPrimesVec(vector<int>& vec){
for (int i = 0; i < vec.size(); i++){
for (int j = 0; j<INT_MAX; j++){
if (isPrime(j)){
vec.push_back(j);}
else{continue;}
}
}
return vec[0];
}
int main(){
int c[15];
size_t szc = sizeof(c)/sizeof(*c);
vector<int> d(szc,0);
cout << fillWithPrimesVec(d);
return 0;
}
Could anyone please help me?

SIGSEGV when sorting array with C++ [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 3 years ago.
Improve this question
I tried sorting this array in ascending order and I got reply saying RUNTIME error(SIGSEGV). Can Anybody explain ?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, arr[1000];
cin >> n;
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
sort(arr, arr + n);
for (int i = 0; i < n; i++)
cout << arr[i] << endl;
return 0;
}
When you get input from a user that is used to populate an array, you should always validate the input before using it. If the user wants to enter 1001 numbers or more, or even a negative amount, you will access the array out of bounds and your program has undefined behaviour.
A better alternative is to use a std::vector to allocate just as much space as you need. One possible solution:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
size_t n;
if(std::cin >> n) { // check that the user actually entered a number
std::vector<int> arr(n); // create a vector with n elements
for(size_t i=0; i<n; ++i)
std::cin >> arr[i];
std::sort(std::begin(arr), std::end(arr));
for(size_t i=0; i<n; ++i)
std::cout << arr[i] << '\n';
}
}
You're allocating space for only 1000 elements, thereby causing segmentation fault if n is more than that, because scanf will try to put 1001-th element in memory location un-allocated to arr. Since you're using C++, Please use std:vector to avoid such pitfalls.

Code is printing only one multiple instead of 3 [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 3 years ago.
Improve this question
I was writing a code which displayed first three multiples of an integer using functions. But here when I run this it shows only the first multiple.
#include <iostream>
#include <vector>
// Defined first_three_multiples() here:
std::vector <int> first_three_multiples(int num) {
std::vector <int> output;
for (int i=1; i<4; i++) {
output.push_back(num*i);
return output;
}
}
int main() {
for (int element : first_three_multiples(8)) {
std::cout << element << "\n";
}
}
Expected Output: 8 16 24
Actual Output: 8
You have put the return statement inside the for loop. It is advised to follow proper code indentations in order to avoid these kind of errors from happening again.
#include <iostream>
#include <vector>
std::vector<int> first_three_multiples(int num)
{
std::vector<int> output;
for (int i = 1; i < 4; i++) {
output.push_back(num * i);
# you put a return statement here, which returns only 8
}
return output; # this would return all three values
}
int main()
{
for (int element : first_three_multiples(8)) {
std::cout << element << "\n";
}
}
Simple error
for (int i=1; i<4; i++) {
output.push_back(num*i);
return output;
}
should be
for (int i=1; i<4; i++) {
output.push_back(num*i);
}
return output;
It pays to get your indentation right as it makes errors like this much easier to spot (and avoid in the first place).

c++ Replacing character with a number [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 7 years ago.
Improve this question
I have this code. What i wanted to do is to replace every letter from every char with indicated number. Like for A is 10, and so on until J, 19. My code works well if i have only one letter in my char array, but if i have more after another it copies useless things. I think that something is wrong with strncat.
#include<conio.h>
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char litera[11]={"ABCDEFGHIJ"};
char cifra[11]={"0123456789"};
char rezultat[256]={0};
int n;cin>>n;cin.get();
for(int i=0;i<n;i++)
{
char x[256];
cin.get(x,256);cin.get();
int k=strlen(x);
for(int j=0;j<k;j++)
{
int p = strchr(litera,x[j])-litera;
if(p>=0 )
{
strncat(rezultat, x,j);
// my p is the indicator for letter and number
strcat(rezultat,"1");
// I'm copying an 1 there because i have numbers
// between 10-19 and in my int array i have only
// the second cipher
strcpy(x,x+j);
rezultat[strlen(rezultat)]=cifra[p];
}
}
cout<<rezultat<<endl;
memset(rezultat,0,sizeof(rezultat));
}
getch();
return 0;
}
Input: 07B, 1AA, C8A
Output: 0711, 11010, 12810
My output:
0711
110AA1
12C810
If you guys can tell me where the problem is, you'll help me a lot, every suggestion is well received, even if is not about this problem. Thanks!
If it is allowed to use vector and string then you can try the following (I tested it and it works.) The input here should be line by line(each line is a new string to be converted) but of course you may modify this part based on your input format:
Include those:
#include <vector>
#include <iostream>
#include <string>
//#include <conio.h>
//#include <cstring>
//using namespace std;
int main()
{
int n;
std::cin >> n;
while (n--)
{
string input;
std::cin >> input;
vector<char> resultat;
for (int i = 0; i < input.size(); i++)
{
if (input.at(i) >= 'A' && input.at(i) <= 'J') // it is a letter between A and J
{
int number = input.at(i) - 'A' + 10;
char ones = (char)(((int)'0') + (number % 10));
char tens = (char)(((int)'0') + (number / 10));
resultat.push_back(tens);
resultat.push_back(ones);
}
else
resultat.push_back(input.at(i));
}
for (int i = 0; i < resultat.size(); i++)
{
std::cout << resultat[i];
}
std::cout << endl;
}
}
if string is not allowed just use your character array. There seems to be nothing wrong in your input format.
If vector is not allowed either, then you may create a char pointer the initialize it based on the final size.
For example:
int newSize=0;
for (int i = 0; i < input.size(); i++)
{
if (input.at(i) >= 'A' && input.at(i) <= 'J')
newSize+=2;
else
newSize++;
}
char* resultat = new char[newSize];
...
Then just fill the resultat.
Hope that helps!
Do you have to do it with your multiple arrays? You could perform a switch-case for only specified inputs. Since you are replacing letters A-J with numbers 10-19, you can easily implement this in switch case. You can also check for incorrect input as well.
If you have to use arrays, first question is why is you numerical array the single digits? Is this is constraint? Cant you use :
char cifra[11]={"10","11","12","13","14","15","16","17","18","19"};
for the array instead, that way you can refer to the array index and replace it using the index? This way, you can compliment the arrays by just using index referencing to replace the output based on the index, such as A is index 1 for alphabetical array which refers to index 1 of the numerical array which is "10" so you just print the array index value to a variable and output it.

Filling an 2D array with pseudo-random numbers [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 8 years ago.
Improve this question
I'm new to C++ and trying to populate and output a 12x12 array using pseudo-random numbers.
Can anyone see where the code is failing?
Code:
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <random>
using namespace std;
const int i = 12;
const int j = 12;
int myArray [i] [j] = {0};
void generateArray();
int main()
{
generateArray();
return 0;
}
void generateArray()
{
srand(1234);
for(int i=0; i < 12; i++);
{
for(int j=0; j < 12; j++);
{
myArray[i][j]= rand();
}
cout << myArray[i][j] << " ";
}
}
Thanks,
Ryan
Your for loops have semicolons after their closing parentheses.
This will effectively treat the for loop as an empty body (and just ignore the loop in general).
Remove them and the code should execute.
Your for loop should look as below.
for(int i=0; i < 12; ++i)
{
for(int j=0; j < 12; ++j)
{
myArray[i][j]= rand();
cout << myArray[i][j] << " ";
}
cout << endl;
}