I can't figure out how to check if an integer (x) is found inside a string (num). The if (num[i] == x) doesn't work. Can somebody please help me? Also I'm new to coding/ c++ and barely know the basics, so an easy-to-understand answer would be appreciated! Thank you!
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int n, x;
cin >> n >> x;
string num;
int count = 0;
for (int i = 1; i <= n; i++) {
num.append(to_string(i));
}
for (int i = 0; i <= num.size(); i++) {
if (num[i] == x) {
count += 1;
}
}
cout << num;
cout << count;
}
I tried converting it to a string, making a new string, and converting it to a char (not sure how this stuff works), but it keeps giving me the same error or it just doesn't run the way I was expecting. The count doesn't go up, and stays at zero.
Convert x to a string and then use the string::find() method to search for it in num, eg
auto index = num.find(to_string(x));
if (index != string::npos) {
// found
} else {
// not found
}
Related
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;
}
I'm looking to convert a for loop of int 1-9 to a string array, having looked around I've found some code to convert an int to a string but when I've tried to put it inside a for loop and make a string array I've been getting errors.
I've been given an assertion failure when I tried this
#include<iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string str[9];
for (int a = 1; a <= 9; a++) {
stringstream ss;
ss << a;
str [a] = ss.str();
cout << str[a];
}
return 0;
}
And when I tried this the program kept crashing
#include<iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
ostringstream str1 [9];
for (int num = 1; num <= 9; num++) {
str1[num]<< num;
string geek = str1[num].str();
cout << geek << endl;
}
return 0;
}
Any help would be really appreciated.
c++ uses 0 based indexing. That means string str[9] supports indexes 0->8 not 1->9. In this loop:
for (int num = 1; num <= 9; num++) {
you are attempting to index from 1->9. You should change it to this:
for (int num = 0; num < 9; num++) {
to loop over the whole array. Or better yet use:
std::vector<std::string> str(9); // For dynamic storage duration
std::array<std::string, 9> str; // For automatic storage duration
int num = 1;
for (auto& currentString : str) {
currentStr << num++
}
I think that this is the cause of the crash:
for (int num = 1; num <= 9; num++)
just change the operator to be "<9" instead of "<=9" :
for (int num = 1; num < 9; num++)
I am trying to solve the 'Copy-Paste' programming problem (https://www.codechef.com/problems/RRCOPY ) of codechef
Here is what I have tried
#include <iostream>
using namespace std;
bool isNumberInArray(int array[], int A, int size)
{
bool isFound = false;
for(int i = 0; i < size; i++)
{
if(array[i] == A)
{
isFound = true;
break;
}
}
return isFound;
}
int main()
{
int T, i = 0, A, size = 0, count;
int array[100000];
cin >> T;
while(T--)
{
cin >> size;
count = 0;
i = 0;
while(size--)
{
cin >> A;
if(isNumberInArray(array, A, count) == false)
{
array[i] = A;
count++;
}
i++;
}
cout << count << endl;
}
return 0;
}
Can anyone please tell what I am doing wrong.
Thanks in advance.
There are three mistakes in your program.
First: Why is the variable i outside the if block. You are incrementing the index even if there are duplicates in your array. (You can just use count instead of i).
array[count]=A;
count++;
Second: You shouldn't print the result immediately after evaluating a testcase. You need to store all the results of all testcases in an array, and print them after you solve all of them.
Third: Your algorithm runs on O(n^2) which will definitely result in a TLE.
You need to improve your algorithm to O(n). My solution:https://www.codechef.com/viewsolution/9011078
Next time please be more concise about what you want to ask.
Please read the task first: http://codeabbey.com/index/task_view/neumanns-random-generator
I have to keep track of the number of iterations, but I get very strange results. In the example after the task we have the numbers 0001 and 4100 and they should come to loop after 2 and 4 iterations. But my results are 1, 4 or if I change the place of the counter 2 or 5 but never 2 and 4. Here is my code:
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
int value;
int counter;
int result;
int setvalue = 1; // use to exit the loop if setvalue == 0;
cin >> n;
vector<int> new_results(0); // use to store all the results from iterations
vector<int> results_vec(0); // use to store the number of iterations for each number
for (int i = 0; i < n ; i++)
{
cin >> value;
while(setvalue == 1)
{
value = value*value;
value = (value % 1000000) / 100;
if(find(results_vec.begin(), results_vec.end(), value) == results_vec.end())
{
results_vec.push_back(value);
}
else
{
counter = results_vec.size();
new_results.push_back(counter);
setvalue = 0;
}
}
results_vec.clear();
}
for (int i = 0; i < new_results.size() ; i++)
{
cout << new_results[i] << " ";
}
}
Going in and out of a string the way you have is really very ugly and extremely expensive computationally.
Use
(value % 1000000) / 100;
instead to extract the middle four digits. This works by (1) taking the modulus to remove the leading two digits then (2) removing the last two with integer division.
As it's so much simpler, I suspect that will fix your bugs too.
Here is the correct code, thank you for all your help.
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
int value;
int counter;
int result;
cin >> n;
vector<int> new_results(0); // use to store all the results from iterations
vector<int> results_vec(0); // use to store the number of iterations for each number
for (int i = 0; i < n ; i++)
{
cin >> value;
results_vec.push_back(value);
while(true)
{
value = value*value;
value = (value % 1000000) / 100;
if(find(results_vec.begin(), results_vec.end(), value) == results_vec.end())
{
results_vec.push_back(value);
}
else
{
counter = results_vec.size();
new_results.push_back(counter);
break;
}
}
results_vec.clear();
}
for (int i = 0; i < new_results.size() ; i++)
{
cout << new_results[i] << " ";
}
}
I'm trying some exercise to learn the use of pointers with arrays and functions.
So I tried to code a "strange way" to find out primes within a certain range.
The problem is that the output always add the return value of the function with the algorithm for the primes. if I omit it, it shows is '32767', if I write return *pt, it adds the last number of the range, even if it's not a prime!
Just tried it with number 6: it's not a prime but it pops up!
#include <iostream>
int show_primes(const int * begin, const int * end);
int main()
{
using namespace std;
int i = 0;
int End_Array = 0;
cout << "Write the last number in your range (it always start from number 2)";
cin >> End_Array;
i=End_Array;
int cookies[i];
for(i=-1; i<End_Array; i++)
cookies[i] = i+1;
cout << show_primes(cookies, cookies + End_Array-1);
}
int show_primes (const int * begin, const int * end)
{
using namespace std;
const int * pt;
int z = 0;
for (pt = begin; pt < end; pt++, z=0)
{
for (int n=2; n<=*pt; n++)
if ( *pt%n == 0 )
++z;
if (z==1)
cout << *pt <<endl;
}
return *pt ;
}
Your loop is accessing a value at negative index.
cookies[i] = i+1; //For first iteration, value of i is -1
So for(i=-1; i<End_Array; i++) should be changed to for(i=0; i<End_Array; i++)
Also, you do not need to return from the function as you are printing the values within itself
Although you are using pointers for your learning, a more simpler implementation would be:
#include <iostream>
using namespace std;
void show_primes(int num)
{
bool flag = false;
for (int pt = 2; pt < num; pt++)
{
if ( num%pt == 0 )
{
flag = true;
break;
}
}
if(!flag)
{
cout<<num<<' ';
}
}
int main()
{
int End_Array = 0;
cout << "Write the last number in your range(>2)";
cin >> End_Array;
for(int i=2; i<End_Array; i++)
{
show_primes(i);
}
}
P.S.: Can someone please highlight that is it a bad practice to include std namespace in every functional block as OP has done.(I think it is)
for(i=0; i<End_Array; i++) // Start from zero
cookies[i] = i; //Use i
// Don't use cout
show_primes(cookies, cookies + End_Array-1);