Getting segmentation-fault when trying to assign character from getline - c++

So, I'm getting sentence using getline(cin, str); then string text[str.length()]; and after this in for statement when i want to combine them ( text[e] = text[e] + str[i]; ) I'm getting segmentation-fault. Full Code:
#include <cstdlib>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
string str;
int i, e, space = 0;
getline(cin, str);
string text[str.length()];
for(i=0; i<str.length(); i++) {
if(str[i]==' ') {
space++;
e++;
}
else {
text[e] = text[e] + str[i];
}
}
return 0;
}

e is unitialized, and it will be holding a random value probably out of bounds of text causing the segmentation fault. This does not initialize all variables to zero:
int i, e, space = 0;
only space is initialized to zero. Change to:
int i = 0, e = 0, space = 0;
or:
int i = 0;
int e = 0;
int space = 0;
To my knowledge, c++ does not support variable length arrays.

Related

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

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++ how print how many element are repeated in 2 array?

I have two arrays and I want to count how many elements are same between two arrays.
I try many times but the output is not correct. The correct should be 6 times
but the output is 4 times in the code.
Note: if s1 is "ss" and s2 is "ss", is the result 2
Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main() {
char s1[] = "FOOBART";
char s2[] = "BFORATO";
int flag=0;
for(int i=0, j=0; i < sizeof(s1) && j < sizeof(s2); ) {
if(s1[i] == s2[j]) {
flag++;
i++;
j++;
} else if(s1[i] < s2[j]) {
i++;
} else {
j++;
}
}
cout << flag;
}
All elements of s1 are present in both strings so the output will be equal to the length of s1. Here is the correct code
#include <iostream>
using namespace std;
int main() {
char s1[] = "FOOBART";
char s2[] = "BFORATO";
int count=0;
for (int i=0; i<sizeof(s1)-1; i++) {
for (int j=0; j<sizeof(s2)-1; j++) {
if (s1[i]==s2[j]) {
count++;
break;
}
}
}
cout<<count<<endl;
}
Hope this will help you
solution using stl algorithms:
#include <iostream>
#include <algorithm>
#include <string>
int main()
{
const std::string s1 = "FOOBART";
std::string s2 = "BFORATO";
int count = 0;
auto beg = begin(s2);
for(auto& elm : s1)
{
auto x = find(beg, end(s2), elm);
if(x != end(s2))
{
*x = *beg;//get rid of elment and reduce the range of search.
++beg;
++count;
}
}
std::cout << count;
return 0;
}

Stringstream trouble

so,i'm trying to do a conversion(integer to string) and then add this string
with another.But it seems stringstream is not working..(it's normally working but the loop causes troubles)
I'm done with google
& almost tried everything but can't get this code to work..Anyone help me :( ?
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cin>>n;
string arr[n];
string a;
int i=0;
int s;
int c;
cin>>a;
arr[i] = a;
i++;
cout<<"OK"<<endl;
n--;
while(n--)
{
cin>>a;
s = 0;
for(int j=0;j<i;j++)
{
if(arr[j] == a)
{
s = 1;
break;
}
}
i++;
if(s == 0)
{
arr[i] = a;
cout<<"OK"<<endl;
}
else
{
c++;
stringstream ss;
ss<<c;
string m = ss.str();
a+=m;
arr[i] = a;
cout<<a<<endl;
ss.str("");
ss.clear();
}
}
return 0;
}
c is uninitialized, you should initialize it, and also s before using:
int s = 0;
int c = 0;
You can't use non-const variables for array initialization, consider writing:
constexpr int MAX_STRINGS = 5;
string arr[MAX_STRINGS];
The loop trouble is here:
i++
You're going over the boundaries at the last element. Just move i++ to the end of while loop.

Reversing a word : C++

I want to reverse a char string in c++.
I wrote this code:
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80];
int i, j;
int l;
l = strlen(word);
for(i = 0, j = l; i < l-1; i++, j--){
word[j] = rev[i];
}
cout << rev << endl;
return 0;
}
In terminal it shows some characters like this:
83???uH??? ... Something like this
Your character array rev is not zero terminated.
And istead of to write to rev you are writing to word.:)
word[j] = rev[i];
The loop is also wrong due to condition
i < l-1;
There must be
i < l;
The program can look the following way
#include <iostream>
#include <cstring>
int main()
{
char word[80] = "polymorphism";
char rev[80];
size_t n = std::strlen( word );
size_t i = 0;
for ( ; i < n; i++ ) rev[i] = word[n - i - 1];
rev[i] = '\0';
std::cout << word << std::endl;
std::cout << rev << std::endl;
return 0;
}
The program output is
polymorphism
msihpromylop
Take into account that you can do the same using standard algorithm std::reverse_copy declared in header <algorithm>.
For example
#include <iostream>
#include <cstring>
#include <algorithm>
int main()
{
char word[80] = "polymorphism";
char rev[80];
size_t n = std::strlen( word );
*std::reverse_copy( word, word + n, rev ) = '\0';
std::cout << word << std::endl;
std::cout << rev << std::endl;
return 0;
}
The program output is the same as above
polymorphism
msihpromylop
There are 3 changes I made to your code:
Change 1: Since string length is l, indexing will be from 0 t ol-1.
Change 2: rev will be storing the values from word, not the other way round.
Change 3: A proper string should be \0 terminated.
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80]="";
int i, j;
int l;
l = strlen(word);
for(i = 0, j = l-1; i < l; i++, j--){ //change 1
rev[i] = word[j]; // change 2
}
rev[i]='\0'; // change 3
cout<<rev;
return 0;
}
Working ideone link: http://ideone.com/kIqeNF
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80] = {'\0'};
int i = 0;
int last = strlen(word) - 1;
while(last >= 0) {
rev[i] = word[last];
i++;
last--;
}
cout << rev << endl;
return 0;
}