Error trying to convert string char into int - c++

I have a simple program where I want to store the input into matrices for easy access. I am having trouble converting a simple string character into an int, can someone explain why my code is giving me this message when I try and compile?
acm.cpp:20:42: error: request for member ‘c_str’ in ‘temp.std::basic_string<_CharT, _Traits, _Alloc>::operator[]<char, std::char_traits<char>, std::allocator<char> >(((std::basic_string<char>::size_type)j))’, which is of non-class type ‘char’
The problem seems to be with my use of the c_str() function, but if i'm not mistaken this is necessary for converting characters into int values.
My code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// read input from console
int N, M;
cin >> N; // number of people
cin >> M; // max number of topics
// read in binary numbers into matrix
int binaryNumbers[N][M];
for (int i = 0; i < N; i++) {
string temp;
cin >> temp;
for (int j = 0; j < M; j++) {
binaryNumbers[i][j] = atoi(temp[j].c_str());
cout << binaryNumbers[i][j] << endl;
}
}
return 0;
}

Use:
binaryNumbers[i][j] = temp[j] - '0';
You don't need to use atoi for a single digit, its numeric value is simply its offset from '0'.
But if you really want to use atoi, you will have to create a separate string:
for (int j = 0; j < M; j++) {
char digit[2] = "0";
digit[0] = temp[j];
binaryNumbers[i][j] = atoi(digit);
cout << binaryNumbers[i][j] << endl;
}

Related

Why does this code output before even reading input?

My code below outputs 0, the value of max_explode, before even reading in my input. Why is this happening?
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX 100
using namespace std;
int N,cnt=0;
vector<int> arr;
bool seen[MAX+1];
int main()
{
for (int i = 0; i < N; i++) seen[i]=false;
int max_explode=0;
for (int i = 0; i < N; i++)
{
int cow;
cin >> cow;
arr.push_back(cow);
}
sort(arr.begin(),arr.end());
cout << max_explode << "\n";
return 0;
}
You read input in a loop:
for (int i = 0; i < N; i++)
{
int cow;
cin >> cow;
arr.push_back(cow);
}
However, N is never explicitly initialized. Since it's a global variable, it's automatically initialized to 0, and your loop never runs.
There's a small issue in your 7th line to be specific. You have defined the variable N but haven't initialized a value to it.

Unable to print the string (C++)

I am unable to print the string after assigning every value of one string to another string. How to overcome this problem
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, k;
string s = "Nikhil", shiftedS;
n = s.length();
cin >> k;
for (int i = 0; i < n; i++)
{
int idx = (i + k) % n;
shiftedS[idx] = s[i];
}
shiftedS[n] = '\0';
for (int i = 0; i < n; i++)
cout << shiftedS[i] << " ";
cout << shiftedS; // I am unable to print when I try like this.
return 0;
}
You are getting unpredictable behavior because shiftedS is an empty string. If you initialize it like this
string shiftedS(n, ' '); // n is equal to length of "Nikhil"
and get rid of shiftedS[n] = '\0'; (C++ string object doesn't need this), it should work as expected. I tried it out with these changes and it worked for me.
why don't you try like this
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,k;
string s="Nikhil",shiftedS = "";
n=s.length();
cin>>k;
for(int i=0;i<n;i++)
{
int idx=(i+k)%n;
shiftedS+=s[i];
}
cout<<shiftedS;
return 0;
}

C++ Array of Pointers not assignable

I need to create 2 arrays, each with 4 elements. One array contains four int values gotten from the user, and the other array contains pointers to the elements of the first array. I keep getting the following error:
array type 'int *[4]' is not assignable
on this line:
my_ptrs = &my_ints;
Here is my code:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int my_ints[4];
int *my_ptrs[4];
float temp;
int num;
for (int x=0; x< 4; x++)
{
cout << "Enter Integer:" << endl;
cin >> num;
my_ints[x] = num;
}
my_ptrs = &my_ints;
for(int k=0; k<=3; k++)
{
for(int j=k+1; j<=3; j++)
{
if(my_ptrs[k]>my_ptrs[j])
{
temp=*my_ptrs[k];
my_ptrs[k]=my_ptrs[j];
*my_ptrs[j]=temp;
}
}
cout << my_ptrs[k] << " ";
}
return 0;
}
Your apparent intent is to have each pointer in my_ptrs to point to the corresponding value in my_ints.
I'm afraid there are no shortcuts here, using a single assignment. You have to do it the hard way:
for (int i=0; i<4; ++i)
my_ptrs[i]=&my_ints[i];
You cannot assign a pointer-to-an-array to an array variable, like you are trying to do. But what you can do instead is either:
initialize the second array in its declaration directly:
int my_ints[4];
int* my_ptrs[4] = {&my_ints[0], &my_ints[1], &my_ints[2], &my_ints[3]};
populate the array in a separate loop:
int my_ints[4];
int* my_ptrs[4];
for (int i = 0; i < 4; ++i)
my_ptrs[i] = &my_ints[i];
That being said, based on what you are trying to do ("i want to print the my_ptrs array in ascending order"), you could just get rid of the second array altogether and use the std::sort() algorithm instead:
Sorts the elements in the range [first, last) in ascending order.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int my_ints[4];
for (int x = 0; x < 4; ++x)
{
cout << "Enter Integer:" << endl;
cin >> my_ints[x];
}
std::sort(my_ints, my_ints+4);
for(int k = 0; k < 4; ++k)
cout << my_ints[k] << " ";
return 0;
}

Picking about random character without repetition c++

I need to pick m amount of random characters(letters) without repetition and im completely stuck, i keep getting only 1 random letter. How can i fix my code? Is there even a way to fix this or should i just scrap this idea and look for a solution from some kinf od tutorials?
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
cout << "number below 27" << endl;
int m;
cin >> m;
srand(time(NULL));
bool repeat = false;
char letters[m];
char letter;
for(int i = 0; i < m; i++){
letter = rand()%26 +97;
repeat = true;
for(int j = 0; j < m; j++){
if(letters[m] == letters[j]){
repeat = false;
break;
}
}
if(repeat){
letters[m] = letter;
}
}
for (int i = 0; i < m; i++){
cout << letters[m];
}
}
You can use suffle -
#include <random>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main ()
{
char charSet[]={'a','b','c'};//You can add all the charecters
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(charSet,charSet+3,g);
for(auto c : charSet)
{
std::cout<<c;
}
std::cout<<endl;
return 0;
}
bool repeat = false;
vector<char> letters(m);
char letter;
for(int i = 0; i < m; i++){
do
{
repeat = false;
letter = rand()%26 +97; // generate new random number
for(int j = 0; j<=i; j++) // iterate through the already generated numbers
{
if (letter == letters[j]){ // if the generated number already exists, do the while again
repeat = true;
break;
}
}
} while(repeat);
letters[i] = letter; // assign the unique number
cout << letter;
repeat = false;
}
You repeat the random number generator until you have a unique random number.
And to output your values use i because m is constant and out of bounds:
for (int i = 0; i < m; i++){
cout << letters[i];
}
I think the direct method is to use set in C++. The following solution is done just now utilising set to ensure the unique. Hope it could be helpful.
#include <iostream>
#include <ctime>
#include <set>
#include <random>
using namespace std;
int main()
{
cout << "number below 27" << endl;
int m;
cin >> m;
srand(time(NULL));
set<char> letters_set;
while(letters_set.size() < m){
char c = rand()%26+'a';
letters_set.insert(c);
}
for(auto c: letters_set)
cout<<c<<endl;
}
A more efficient solution which also ensure the equal possibility for each letter.
#include <iostream>
#include <ctime>
#include <set>
#include <random>
using namespace std;
int main()
{
cout << "number below 27" << endl;
int m;
cin >> m;
srand(time(NULL));
vector<int> all_letters(26, 'a');
for(int i = 0; i < 26; ++i) all_letters[i] += i;
vector<char> letters_set;
for(int i = 0; i < m; ++i){
int select = rand()%all_letters.size();
letters_set.push_back(all_letters[select]);
all_letters.erase(all_letters.begin()+select);
}
for(auto c: letters_set)
cout<<c<<endl;
}
There is an obvious error in the logic of your code: when you test for repetition you compare to the beyond the end letter only, instead to all those sampled so far. The correct test would be
for(int i = 0; i < m; i++) {
bool repeating;
char tryletter;
do {
tryletter = rand()%26 +97;
repeating = false;
for(auto j=0; j!=i && !repeating; ++j)
repeating = tryletter == letters[j];
} while(repeating);
letters[i] = tryletter;
}
Though this is not the most efficient way to do what you've been asked to do. A more efficient way would be to start with all 26 letters, pick one at random and remove it from the set, then continue to pick and remove random letters. For example
std::string random_letters_without_repetition(std::size_t m)
{
std::string letters;
std::string all = "abcdefghijklmnopqrstuvwxyz";
assert(m <= all.size());
std::random_device r;
std::default_random_engine rng(r());
while(m--) {
std::uniform_int_distribution<std::size_t> uni{0,all.size()-1};
auto index = uni(rng);
letters += all[index];
all.erase(index);
}
return letters;
}

Convert char* to <string>

This is my first post, so please be understanding for me :)
I would like to use vector of strings to make sort data easy, but I need this string also to function fun1. So I would like to convert char* word to string str but i can't manage to do it. I was searching answer for my question but I didn't find.
Please help, here is code:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <string.h>
using namespace std;
vector <string> tab;
vector <string> tab2;
int l['Z'+1];
void fun1(char *t)
{
for(int i = 0; t[i]; i++)
l[t[i]]++;
int j = 0;
for(int i = 'A'; i <= 'Z'; i++)
if(l[i])
{
t[j++] = i;
l[i--]--;
}
}
int main()
{
char * word;
string str;
ios_base::sync_with_stdio(0);
int z;
int n;
cin >> z;
while(z--)
{
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> word;
fun1(word);
str.assign(word, sizeof(word));
tab.push_back(str);
}
sort(tab.begin(), tab.end());
for(int i = 0; i < tab.size(); i++)
cout << tab[i] << endl;
}
}
Firstly, I have no idea, why you want to convert char* to string. In your solution firstly you have to allocate memory for chars
char *word = new char[HOW_MANY_CHARS]
But there is better solution. You can write:
cin >> str;
fun1(str);
tab.push_back(str);
And you have to change fun1 to:
void fun1(string &t);