Printing specific characters from a char Array - c++

Im working on this program where a user will enter a "S" or "Sell, and the program looks for those cstring values in the char array and If found will return the menu option starting from the first '\n' and the last '\n'. So entering 'S' or 'Se' will return '2. Sell'. This is where I'm stuck on.
UPDATED! Now just trying to see if I can pull in that '#. ' when a solution is selected? (if possible)
#include "pch.h"
#include <iostream>
#include <cstring>
using namespace std;
void promptForInput(char list[]) {
char *strPtr = nullptr;
const int ANSW = 10;
char line[ANSW];
int num = 0;
cout << "Enter an option: ";
cin.getline(line, ANSW);
strPtr = strstr(list, line);
while (strPtr[num] != '\n' && strPtr[num] != '\0')
{
cout << strPtr[num];
num++;
}
}
int main()
{
int count = 0;
char menu[] = "1. Buy\n2. Sell\n3. Convert\nX. Exit\n";
while (menu[count]){
cout << menu[count];
count++;
}
promptForInput(menu);
}

Related

find a certain word in sentence in c++

I want to write a program that finds a word that the user entered I think my solution is right but when I Run it, the program shows nothing in the console
anybody can fix it?
int main()
{
char sen[200],del[200],maybedel[200];
cout<<"enter sentence :"<<endl;
cin.getline(sen,200);
cout<<"which word do you want to delete ?";
cin.getline(del,200);
int len = strlen(sen);
for(int i=0;i<=len;i++)
{
if(sen[i]==' ')
{
for(int j=i;j<=len;j++)
if(sen[j]==' ' || sen[j]=='\0')
for(int k=i+1,t=0;k<j;k++,t++)
maybedel[t]=sen[k];
if(maybedel==del)
cout<<maybedel;
}
}
return 0;
}
The line if(sen[i]==' '), line 12 of your code , prevents code from entering the block unless the sentence begins with (' ')!
I changed the code a bit and now it works fine.
char sen[200], del[200], maybedel[200];
cout << "enter sentence :" << endl;
cin.getline(sen, 200);
cout << "which word do you want to delete ?" << endl;
cin.getline(del, 200);
int len = strlen(sen);
int t = 0;
for(int i = 0; i <= len; i++) {
if(sen[i] == ' ' || sen[i] == '\0') {
maybedel[t] = '\0';
t = 0;
if(strcmp(del,maybedel)==0) {
cout << maybedel << endl;
}
}
else
{
maybedel[t] = sen[i];
t++;
}
}
The major reason for no output is
if (maybedel == del) // <<< this will *never* be true
cout << maybedel; // will never run
Since comparing "strings" in arrays needs help from std::strcmp(maybedel,del) == 0 would be better.
UPDATE:
Another attack method is to avoid raw loops and utilize the STL to your favor. Here's a more robust solution:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
using namespace std;
int main() {
cout << "enter sentence :\n";
string sen;
if (!getline(cin, sen)) throw std::runtime_error("Unable to read sentence");
cout << "which word do you want to delete ? ";
string del;
if (!(cin >> del)) throw std::runtime_error("Unable to read delete word");
istringstream stream_sen(sen);
vector<string> arrayofkeptwords;
remove_copy_if(istream_iterator<string>(stream_sen), istream_iterator<string>(),
back_inserter(arrayofkeptwords),
[&del](auto const &maybedel) { return maybedel == del; });
copy(begin(arrayofkeptwords), end(arrayofkeptwords),
ostream_iterator<string>(cout, " "));
cout << '\n';
}

Why is my C++ program only printing one character?

This program is suppose to generate passwords and compare to what the user inputed, if they match it breaks the while loop and outputs the user's input, but for some reason, the generated passwords are just one characters. I am new to C++, I just started like last Friday.
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
string Password, Passwords;
cout << "Enter a password: ";
getline(cin, Password);
sleep(.7);
system("clear");
while(Password.compare(Passwords)!= 0)
{
for (int x = 0; x <= Password.length(); x++)
{
for (char Alpha = 'a'; Alpha <= 'z'; Alpha++)
{
if(Alpha == 'z')
{
Alpha = 'a';
}
for(int I=0; I <= 10; I++)
{
Passwords = Alpha + I;
system("clear");
sleep(.7);
cout << Passwords <<endl;
}
}
}
}
cout << "Password found: " << Passwords <<endl;
return 0;
}
After a long back and forward in the comments, the OP explained what was his purpose. To generate random words of the same size as input and stop when it matched the input.
This code does what you want. It's in c++14 so you need a recent compiler and to set the c++14 option. Please note the actual use of random.
#include <iostream>
#include <string>
#include <random>
#include <algorithm>
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
class RandomCharGenerator {
private:
static std::string s_chars_;
private:
std::random_device rd_{};
std::default_random_engine r_eng_{rd_()};
std::uniform_int_distribution<int> char_dist_{
0, static_cast<int>(s_chars_.size())};
public:
RandomCharGenerator() = default;
auto getRandomChar() -> char { return s_chars_[char_dist_(r_eng_)]; }
auto setRandomString(std::string &str) -> void {
std::generate(std::begin(str), std::end(str),
[this] { return this->getRandomChar(); });
}
};
std::string RandomCharGenerator::s_chars_ = "abcdefghijklmnopqrstuvwxyz";
auto main() -> int {
RandomCharGenerator rand_char;
auto input = std::string{};
cin >> input;
auto generated = std::string(input.size(), ' ');
do {
rand_char.setRandomString(generated);
cout << generated << endl;
} while (input != generated);
cout << "We generated what you input" << endl;
return 0;
}
For input longer than 4 characters it takes a long time to generate the input.
Ideone demo
To understand why you had only 1 char in your Passwords:
Passwords = Alpha + I;
Alpha is a char, I is an int. Their sum is an int. This is converted to char when assigning to Passwords which is a string. So Passwords is now a string composed of only one char.
It's not clear what that actual line of code was supposed to do, so can't tell you what would have been the fix. Maybe you meant to append to Passwords. Then you should have written Passwords += Alpha + I.
The code below is an example of what I am trying to make. I did not make the code below, am just giving you and example of what am trying to do in the code above
#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
int main()
{
string password;
string Generated;
cout << "Password to find: ";
cin >> password;
char Alpha[]={'a'-1,'a','a','a','a','a','a','a','a','a'};
while( password.compare(Generated) != 0 )
{
Alpha[0]++;
for(int x=0;x<password.length();x++)
{
if (Alpha[x] == 'z'+1)
{
Alpha[x] = 'a';
Alpha[x + 1]++;
}
}
Generated=Alpha[password.length()-1];
for(int i=password.length()-2; i>=0 ; i-- )
Generated+= Alpha[i];
system("clear");
cout << "Trying: "<< Generated << endl;
}
system("clear");
sleep(1);
cout <<"Access Granted: "<< Generated << endl;
return 0;
}

Trouble with cin.getline and strstr

Im trying to write a simple program that will read in a list of names and allow you to search through them. Im having a problem with my cin.getline and my strstr. Im new to c++ and im have a hard time getting my head around c string and its functions.
The error I get from the cin.getline is cannot convert parameter 1 from 'std::ifstream' to 'char *'
and cannot convert parameter 1 from 'char' to 'char *'
The error I get from the strstr is error C2665: 'strstr' : none of the 2 overloads could convert all the argument types
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
const int SIZE = 50;
int size = 0;
// Array of product descriptions
char phoneDirectory[SIZE];
char name; // For user input
char *strPtr = NULL; // Result from strstr
ifstream inFile;
inFile.open("phonebook");
while (!inFile.fail())
{
cin.getline(inFile,phoneDirectory[size]);
size++;
}
inFile.close();
// Get user input
cout << "Enter a name to search for: ";
cin.getline(name, SIZE);
// Search for the string
int index = 0;
while(index < size)
{
strPtr = strstr(phoneDirectory[index], name);
if (strPtr != NULL)
break;
index++;
}
// Output the result of the search
if (strPtr == NULL)
cout << "No matching names were found.\n";
else
cout << phoneDirectory[index] << endl;
return 0;
}
I cant seem to fix the cin.getline's and the strstr.
char name doesn't represent a string, but 1 single character. The getline function accepts a character pointer and an integer, and in your case you're feeding it a character and an integer.
Also, in c++ I'd suggest using std::string instead of characters array. It's much easier to handle and less error prone.
I've corrected your code to do what I think you're looking for. let me know if that's not what you're looking for:
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
const int SIZE = 50;
int size = 0;
// Array of product descriptions
string phoneDirectory[SIZE];
string name; // For user input
char *strPtr = NULL; // Result from strstr
ifstream inFile;
inFile.open("phonebook");
while (!inFile.fail())
{
getline(inFile, phoneDirectory[size]);
size++;
}
inFile.close();
// Get user input
cout << "Enter a name to search for: ";
getline(cin, name);
// Search for the string
int index = 0;
while(index < size)
{
strPtr = strstr(phoneDirectory[index].c_str(), name.c_str());
if (strPtr != NULL)
break;
index++;
}
// Output the result of the search
if (strPtr == NULL)
cout << "No matching names were found.\n";
else
cout << phoneDirectory[index] << endl;
return 0;
}
If you really want to stick with the characters array, here's what your code should look like:
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
const int DIRECTORY_SIZE = 50;
const int STRING_SIZE = 50;
int size = 0;
// Array of product descriptions
char phoneDirectory[DIRECTORY_SIZE][STRING_SIZE];
char name[STRING_SIZE]; // For user input
char *strPtr = NULL; // Result from strstr
ifstream inFile;
inFile.open("phonebook");
while (!inFile.fail() && size < DIRECTORY_SIZE)
{
inFile.getline(phoneDirectory[size], STRING_SIZE);
size++;
}
inFile.close();
// Get user input
cout << "Enter a name to search for: ";
cin.getline(name, STRING_SIZE);
// Search for the string
int index = 0;
while(index < size)
{
strPtr = strstr(phoneDirectory[index], name);
if (strPtr != NULL)
break;
index++;
}
// Output the result of the search
if (strPtr == NULL)
cout << "No matching names were found.\n";
else
cout << phoneDirectory[index] << endl;
return 0;
}

string subscript out of range 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++;
}

c++ find repeated substring within string

Im trying to find the number of times a substring repeats within a string input but for some reason when I call the function it gives me a weird number. I have already tested the function within main and it works fine but when I make a standalone function it doesn't work.
Thank you in advance
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int checkHope(string word1)
{
int answer;
int counter;
for(int i = 0; word1[i] != '\0'; i++)
{
answer = word1.find("h", i);
if ((word1.find("o", (answer+1)) == i+1) && (word1.find("e", (answer+3)) == i+3)) counter++;
}
return counter;
}
int main()
{
string word1;
cout << "Please enter a word to check how many times the word \"hope\" appears. You can also have any letter instead of p.: ";
getline(cin, word1);
cout << checkHope(word1);
return 0;
}
//This will work,
//Changes initialize counter to 0, add condition to check alphabet 'p' also in if condition
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int checkHope(string word1)
{
int answer;
int counter=0;
for(int i = 0; word1[i] != '\0'; i++)
{
answer = word1.find("h", i);
if ((word1.find("o", (answer+1)) == i+1)
&& (word1.find("p", (answer+2)) == i+2)
&& (word1.find("e", (answer+3)) == i+3))
counter++;
}
return counter;
}
int main()
{
string word1;
cout << "Please enter a word to check how many times the word \"hope\" appears. You can also have any letter instead of p.: ";
getline(cin, word1);
cout << checkHope(word1);
return 0;
}