Unable to print the string (C++) - 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;
}

Related

Searching an array for an element, and appending it to the end of the array if it isn't present

It's a practice problem I'm trying to do, but so far I've had no luck. Here's what I tried so far:
#include <iostream>
using namespace std;
string updateList(char arr[],char key, int n);
int main()
{
char usernames[10];
int sizeOf = 2;
usernames[0] = 'a'; usernames[1] = 'b';
string x = updateList(usernames, 'c', sizeOf);
cout << x;
}
string updateList(char arr[],char key, int n)
{
int arrLength = sizeof(arr)/sizeof(char);
int i;
for (i = 0; i < arrLength; i++) {
if (arr[i] == key) {
return "Username already exists";}
else {
arr[n++] = key;
int arrLength = sizeof(arr)/sizeof(char);
for (i = 0; i < arrLength; i++) {
cout << arr[i];
return "\n Username added";
}
} }
}
Any help would be appreciated.
Problem with your approach is that you are not updating the value of n(sizeOf) and you are using n to add element which will create error.instead of that use pass by reference so that n(i,e here sizeOf will updated) will updated Try something like
#include <iostream>
using namespace std;
string updateList(char arr[],char key, int *n);
int main()
{
char usernames[10];
int sizeOf=2;
usernames[0] = 'a'; usernames[1] = 'b';
string x = updateList(usernames, 'c', &sizeOf);
cout << x;
int updateList(char arr[],char key, int n)
{
int i;
for (i = 0; i < arrLength; i++) {
if (arr[i] == key) {
return "Username already exists";}
else {
arr[n++] = key;
for (i = 0; i < arrLength; i++) {
cout << arr[i];
}
return 0; } }
}
You can either use string or vector in order to keep the array of chars dynamic. This is an example of string and it also acts as an array of characters.
#include <iostream>
using namespace std;
int main()
{
string usernames="ab";
char key = 'b';
int i=0;
for(;i<usernames.size();i++)
if(usernames[i]==key)
{
printf("Key exists already");
break;
}
if(i==usernames.size())
{
usernames.push_back(key);
cout << usernames <<endl;
}
return 0;
}

How to count certain word in string using C++

How to counting the same word in a string
Input
Number of String
String1 = dadymathewdadreadad
String2 = sdgfghhjdjrjjyjjrtfdhe
Search = dad
Output
Number of dad in string1 = 3
Number of dad in string2 = 0
Code:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string str[50];
int n;
cin>>n;
for(int i = 0; i < n;i++) {
cin>>str[i];
}
for(int i = 0; i < 50;i++) {
if(substr(i,4) == "dad"){
n += 1;
}
}
cout<<n;
return 0;
}
ERROR
In function 'int main()':
[Error] 'substr' was not declared in this scope
One trick you could use here would be to just replace the search term (e.g. dad) with empty string, and then compare the length of the string before and after the replacement.
string input = "dadymathewdadreadady";
string search = "dad";
int size_orig = input.size();
replace(string, search, "");
cout << "number of 'dad' is: " << (size_orig - input.size()) / search.size();
You can use the find() member function of std::string, adjusting the start position after every successful find until the end of the string:
#include <string>
int count(const std::string& sentence, const std::string& word)
{
int total = 0;
size_t start = 0;
size_t pos = 0;
while ((pos = sentence.find(word, start)) != std::string::npos)
{
++total;
start = pos + word.size();
}
return total;
}
int main()
{
std::string input = "dadymathewdadreadady";
int c = count(input, "dad");
return 0;
}
Other Solution:
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
string s[50];
int c;
cin>>n;
for (int i=0;i<n;i++){
cin>>s[i];
}
for (int i=0;i<n;i++) {
c=0;
int found=s[i].find("jack");
while(found!=string::npos){
found=s[i].find("jack",found+1);
if(found) c++;
}
cout<<c<<endl;
}
}

Having issues eliminating duplicates and sorting from C++ array outfile

Trying to create a list of unique grades from a text file. Having issues with the output eliminating duplicates. Currently, I am trying to compare the value of each previous array entry to the next and if they are different, output the result to the outfile, but is just outputs an empty file.
I am also curious if there is an easy fix to change the sorting from 'low to high' into 'high to low'. Thank you in advance.
#include <iostream>
#include <string>
#include <limits>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
int testScoreArray[100];
void selectSort(int testScoreArray[], int n);
void fileOutput(int testScoreArray[]);
int main()
{
int n = 100;
ifstream infile;
infile.open("testscoresarrayhomework.txt");
for (int i = 0; i < 100; i++) {
infile >> testScoreArray[i];
}
selectSort(testScoreArray, n);
fileOutput(testScoreArray);
infile.close();
return 0;
}
void selectSort(int testScoreArray[], int n)
{
//pos_min is short for position of min
int pos_min, temp;
for (int i = 0; i < n - 1; i++) {
pos_min = i; //set pos_min to the current index of array
for (int j = i + 1; j < n; j++) {
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
//pos_min will keep track of the index that min is in, this is needed when a swap happens
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i) {
temp = testScoreArray[i];
testScoreArray[i] = testScoreArray[pos_min];
testScoreArray[pos_min] = temp;
}
}
};
void fileOutput(int testScoreArray[])
{
ofstream outfile;
int gradeEvent = 0;
int previousGrade = 0;
outfile.open("testscoresoutput.txt");
outfile << "Test Score Breakdown: ";
outfile << endl
<< "Score / Occurance";
for (int i = 0; i < 100; i++) {
previousGrade = i;
if (previousGrade && previousGrade != i) {
outfile << '\n' << testScoreArray[i] << " / " << gradeEvent;
}
}
outfile.close();
};
You have declared a global variable testScoreArray and the function names use the same variable name for their parameters. It's best to avoid using global variables when possible. You can remove global declaration, then declare testScoreArray in main, and pass it to your functions. Example:
//int testScoreArray[100]; <=== comment out
void selectSort(int *testScoreArray, int n);
void fileOutput(int *testScoreArray, int n); //add array size
int main()
{
int testScoreArray[100]; //<== add testScoreArray in here
int n = sizeof(testScoreArray) / sizeof(testScoreArray[0]);
selectSort(testScoreArray, n);
fileOutput(testScoreArray, n);
...
}
In fileOutput you are basically checking to see if i != i, you need to examine the array, not indexing in the loop:
void fileOutput(int *testScoreArray, int n)
{
ofstream outfile("testscoresoutput.txt");
for(int i = 0; i < n; i++)
if(i && testScoreArray[i] != testScoreArray[i-1])
outfile << testScoreArray[i] << "\n";
};
To revers the sort, simply change the condition in this comparison
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
To:
if(testScoreArray[j] > testScoreArray[pos_min])
pos_min = j;
Technically you would rename the variable to pos_max

Converting an int into string array

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++)

C++ does not want a return value

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);