string subscript out of range c++ - c++

I need a help in a very basic c++ code.
My program is about guessing name game the problem which i faced is in reading string char by char
#include <iostream>
#include <time.h>
#include <iomanip>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
void Play(int, int,int, string[], string[]);
string GetRandomName(int, int, int , string[], string[]);
const int ArrayMax = 100;
void Play(int selection, int FArraySize, int MArraySize,string Female[], string Male[])
{
int MAX_TRIES = 3;
int i=0;
ofstream ofFile;
ifstream InFile;
int num_of_wrong_guesses=0;
char letter;
string GuessedName;
GuessedName = GetRandomName(selection, FArraySize, MArraySize, Female, Male);
cout << "Guess the following name:" << endl;
while (GuessedName[i]!= 0 ){
cout<<"?";
i++;
}
cout << "\nEnter a guess letter? or * to enter the entire name" << endl;
cin >> letter;
return;
}
I don't complete coding...
the problem is in the while loop how can i solve it without using cstring?
could you help me?

int i = 0;
while(GuessedName[i] != 0)
{
cout << "?";
i++;
}
Seems like you are trying to print sequence of ? with the length of the string to guess. But you cannot treat std::string as c-string. When its length is n, GuessedName[n] is string subscript out of range - you cannot access one element past end - it's not null-terminated. Use for loop:
for(int i = 0; i < GuessedName.length(); ++i)
cout << "?";
Or simply:
cout << std::string(GuessedName.length(), '?');

Change the while loop like this:
while (GuessedName[i]){
cout<<"?";
i++;
}

Related

Convert char array to a string with cin.getline(.)

hi guys so my question is how to convert a char array to a string. here is my code:
#include<iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol,256);
cout << lol << endl;;
}
return 0;
}
so I want to convert lol to a string variable like "stringedChar" (if thats even english lol)
so I can do stuff like:
string badwords[2] = {"frick","stupid"};
for (int counter = 0; counter < 2;counter++) {
if(strigedChar == badwords[counter]) {
bool isKicked = true;
cout << "Inappropriate message!\n";
}
}
Sorry im just a c++ begginer lol
Do something like this :
as char lol[128];
into string like: std::string str(lol);
Line : cin.getline(lol,256); <--> should be changed to cin.getline(lol,128)
Just invoke std::getline() on a std::string object instead of messing about with a char array, and use std::set<std::string> for badwords as testing set membership is trivial:
#include <iostream>
#include <set>
#include <string>
static std::set<std::string> badwords{
"frick",
"stupid"
};
int main() {
std::string line;
while (std::getline(std::cin, line)) {
if (badwords.count(line) != 0) {
std::cout << "Inappropriate message!\n";
}
}
return 0;
}
Note that this tests whether the entire line is equal to any element of the set, not that the line contains any element of the set, but your code appears to be attempting to do the former anyway.
First off, you have a mistake in your code. You are allocating an array of 128 chars, but you are telling cin.getline() that you allocated 256 chars. So you have a buffer overflow waiting to happen.
That said, std::string has constructors that accept char[] data as input, eg:
#include <iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol, 128);
string s(lol, cin.gcount());
cout << s << endl;;
}
return 0;
}
However, you really should use std::getline() instead, which populates a std::string instead of a char[]:
#include <iostream>
#include <string>
using namespace std;
int main()
{
while (true) {
string lol;
cout << "you say >> ";
getline(cin, lol);
cout << lol << endl;;
}
return 0;
}

Is there a way to search an element of a vector<String>, then check if it contains a particular char, if it does print it

The final element in the vector is the char to search for.
Here’s my code:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
vector<string> words;
string in;
while(cin>>in)
{
words.push_back(in);
}
int size = words.size()
string check = words.at(size-1);
}
I tried your code and the loop was infinite. Try asking a set number of words then use the find method for each string. Here's an example.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> words;
string in;
cout << "Enter 5 words: \n";
for (int i{0}; i < 5; ++i)
{
cout << "Word: ";
cin >> in;
words.push_back(in);
}
cout << "What character do you want to search for? ";
char c;
cin >> c;
for (auto word : words)
{
if (word.find(c) != string::npos)
{
cout << "Character \"" << c << "\" found in " << word << endl;
}
}
return 0;
}
Edit: I noticed that you tried to use int to store the size for the string. Use size_t instead. I also think you meant to use the length method of the string, which also returns size_t.

How to erase non-alphabet characters from a string without going out of range

I am trying to this function to return without numbers, spaces, or other characters and I am supposed to use the .erase function. I understand that my loop keeps going out of range, but I have no clue how to fix it and I've been stuck on this for a while. If the user types "dogs are a lot of fun" and I need the function to return and output "dogsarealotoffun" Thanks for the help.
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
//function to output string without spaces, numbers, or punctuations
string alphabetOnly (string input){
int size;
int i= 0;
size = (int)input.size();
while (input[i] < size){
if (isalpha(input[i])){
i++;
}
else
input.erase(input[i]);
}
return input;
}
int main() {
string input;
cout << "Enter a string to test: ";
getline(cin, input);
cout << "alphabetOnly: " << alphabetOnly(input) << endl;
}
EDITED: I was too hasty in my previous answer (as I am learning I need to speak from tested code rather than off the top of my head) and needed to debug. The problem is in the else case you need to erase the char, NOT increment i because the length of the string just changed, and also since the length of the string changed you need to reset size to be the new length. Sorry for the hasty answer earlier, I was speaking without actually using the compiled code.
#include <iostream>
#include <cctype>
#include <string>
//function to output string without spaces, numbers, or punctuations
std::string alphabetOnly (std::string input){
int size;
int i= 0;
size = (int)input.size();
while (i < size){
if (isalpha(input[i])){
i++;
}
else{
input.erase(i,1);
//do not increment i here since the index changed becauase of erase
size = (int)input.size();
}
}
return input;
}
int main() {
std::string input;
std::cout << "Enter a string to test: ";
std::getline(std::cin, input);
std::cout << input;
std::cout << "alphabetOnly: " << alphabetOnly(input) << std::endl;
return 0;
}
something like this:
#include <iostream>
#include <string>
#include <algorithm>
//function to output string without spaces, numbers, or punctuations
std::string alphabetOnly (std::string input)
{
auto not_alpha = [](char c) { return !std::isalpha(c); };
input.erase(std::remove_if(begin(input),
end(input),
not_alpha),
std::end(input));
return input;
}
int main() {
std::string input;
std::cout << "Enter a string to test: ";
getline(std::cin, input);
std::cout << "alphabetOnly: " << alphabetOnly(input) << std::endl;
}
http://coliru.stacked-crooked.com/a/340465d41ecd8c8e
There's quite a few things wrong with your code, but to start with here's your main error corrected.
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
//function to output string without spaces, numbers, or punctuations
string alphabetOnly (string input){
int size;
int i= 0;
size = (int)input.size();
while (i < size){
if(isalpha(input[i]))
{
i++;
}
else
input.erase(input.begin( ) + i );
}
return input;
}
int main() {
string input;
cout << "Enter a string to test: ";
getline(cin, input);
cout << "alphabetOnly: " << alphabetOnly(input) << endl;
}
But this is awfully inefficient because you swhift all the remaining unchecked characters each time you delete.
You should use something like
input.erase( remove_if( input.begin(), input.end(), not( isalpha ) ), input.end( ));
This is known as the remove-erase idiom, whihc you can lookup anywhere.

Finding the longest common suffix between two strings C++

I'm fairly new to C++ and I can't seem to figure this out.
I get some weird output when running it. I am also trying to do this in the simplest way possible. How would I go about just printing the word in the suffix array and not all of the extra stuff. I have tried multiple ways to do this and they still show up.
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main(){
char word1[80];
char word2[80];
char suffix[80];
cout << "Enter the first word: ";
cin >> word1;
cout << "Enter the first word: ";
cin >> word1;
int len1 = strlen(word1);
int len2 = strlen(word2);
while(len1 > 0 && len2 > 0 && word1[len1] == word2[len2]) {
int k=0;
suffix[k]=word1[len1];
k++;
len1--;
len2--;
}
for(int i=strlen(suffix);i>=0; i--){
cout << suffix[i];
}
getch();
return 0;
}
Several things:
You should better use string instead of an array of char. That way,
you don't have to worry about memory.
The line int k=0; should be outside of the while.
Remember that arrays start at 0, so substract 1 from the length of
the words and iterate whilelen1 >= 0 && len2 >= 0
Using strings, you can use the method substr (reference
here).
Here is a modified version of your code:
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main() {
string word1,word2,suffix;
cout << "Enter the first word: ";
cin >> word1;
cout << "Enter the first word: ";
cin >> word2;
int len1 = word1.size()-1;
int len2 = word2.size()-1;
int k=0;
while(len1 >= 0 && len2 >= 0 && word1[len1] == word2[len2]) {
len1--;
len2--;
k++;
}
suffix=word1.substr(word1.size()-k,k);
cout << suffix;
getch();
return 0;
}
I always think the "simplest way possible" is to use someone else's work. Here
is one way to write your program that leverages the standard library:
#include <algorithm>
#include <string>
#include <iostream>
std::string suffix(const std::string& a, const std::string& b) {
size_t len = std::min(a.size(), b.size());
auto its = std::mismatch(a.rbegin(), a.rbegin()+len, b.rbegin());
return std::string(its.first.base(), a.end());
}
int main () {
std::cout << suffix("December", "May") << "\n";
std::cout << suffix("January", "February") << "\n";
std::cout << suffix("April", "April") << "\n";
}

Using the getword function c++

Am I using the getword function wrong here? The compiler keeps telling me that there is no member function.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
using namespace std;
int OccuranceOfString(ofstream & Out)
{
string Occur;
string Temp;
int OccurLength;
int count;
cout << "please enter to string to search for";
cout << endl;
cin >> Occur;
OccurLength = Occur.length();
while(Out.getword(Temp))
{
if (Temp == Occur)
{
count ++;
}
}
return count;
}
Whats wrong with my code? I'm trying to find all occurances of a string with this function
std::ofstream has no getword function: see here.
Perhaps you're thinking of std::getline.
There is no function getword in the header files listed. You simply must construct a function that will extract words from a line. capture a line by
getline(out,line);
line will have your line of string and use line[index] to get continuous characters to be equal to a word.
You can use this
std::string::find
do something like this..
int pos = 0;
int occurrences = 0
string input = "YAaaaAH";
string find = "a";
while(pos != -1){
pos = input.find(find,pos);
occurrences++;
}
text file :
code :
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream file("DB_name_age.txt");
int index;
string name;
int age;
if(file.is_open())
{
while(file >>index >> name >>age)
{
cout << index <<" "<<name <<" "<<age << endl;
}
}else{
cout<< "file open fail" <<endl;
}
return 0;
}
visual explanation: