Trouble with cin.getline and strstr - c++

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

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

Printing specific characters from a char Array

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

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

error: invalid conversion from 'char*' to 'char' on lines 26,36

I am working on reading a file and formatting array so I can work on them with other stuff but I am stuck in the beginning. It says I can't change from char* to char but my token is not char*.
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <string>
#include <stdio.h>
using namespace std;
void get_input(string teams[][2]) {
string infile;
double value;
char buffer[100];
char token;
stringstream ss;
cout << "Enter the input file: ";
cin >> infile;
ifstream file;
file.open (infile.c_str());
if (file.is_open()) {
int teamcounter = 0;
while (file.getline (buffer, 100)) {
int counter = 0;
token = strtok (buffer, ",");
while (token) {
if (counter == 0) {
teams[teamcounter][counter] = token;
}
else if ((counter == 1) || (counter == 2)) {
ss << token;
ss >> value;
teams[teamcounter][counter] = value;
}
token = strtok (NULL, ",");
counter++;
}
teamcounter++;
}
file.close();
}
else {
cout << "Unable to open file";
}
for (int i = 0; i< 7; i++){
for (int j = 0; j<2;j++){
cout << teams[i][j] << " ";
}
cout << endl;
}
}
Is making my array into string make me unable to put float or double values to them?
int main() {
cout << "Welcome to the football bracket game!" << endl;
string teams[7][2];
get_input(teams);
}
My input text format is like this:
Trojans, 0.80, 0.60
Bruins, 0.20, 0.30
Bears, 0.60, 0.50
Trees, 0.50, 0.40
Ducks, 0.40, 0.80
Beavers, 0.50. 0.10
Huskies, 0.80, 0.40
Cougars, 0.10, 0.90
char token;
token = strtok (buffer, ",");
token is of type char, strtok returns a char*. They are not of the same type and the compiler is complaining (logically) about it. strtok returns the pointer to the next token of the processed input char* so indeed there's no sense in assigning it to a single character.
Compiler is indeed unable to find a way to convert from the returnd char* to char, there's nothing strange in the error.
You defined variable token as having type char
char token;
while function strtok returns an obhect of type char * .So these statements
token = strtok (buffer, ",");
and
token = strtok (NULL, ",");
are invalid. I think you meant
char *token;
Also you defined array teams as an array of elements of type std::string
string teams[7][2];
However in function get_input you try to assign a value of type double to an object of type std::string
double value;
//...
teams[teamcounter][counter] = value;
Also it would be more correct if the function had second parameter that specifies the size of the first dimension of the array
void get_input(string teams[][2], int n );
and would be called as
get_input(teams, 7);
You should check how many lines of the file you entered.
strtok() returns a char* but your token variable is declared as char. It needs to be declared as char* instead.
Update: Since you are using C++, I strongly suggest you use C++, don't mix C and C++ together. Ignore strtok() even exists, eg:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
struct Team
{
std::string Name;
double Value1;
double Value2;
};
void get_input(std::vector<Team> &teams)
{
std::string infile;
std::ifstream file;
std::cout << "Enter the input file: ";
std::cin >> infile;
file.open (infile.c_str());
if (!file.is_open())
{
std::cout << "Unable to open file";
return;
}
std::string line;
while (std::getline(file, line))
{
Team team;
std::istringstream ss(line);
std::string token;
int counter = 0;
while (std::getline(ss, token, ","))
{
switch (counter)
{
case 0:
team.Name = token;
break;
case 1:
std::stringstream(token) >> team.Value1;
break;
case 2:
std::stringstream(token) >> team.Value2;
break;
}
++counter;
}
teams.push_back(team);
}
}
int main()
{
std::cout << "Welcome to the football bracket game!" << std::endl;
std::vector<Team> teams;
get_input(teams);
for (std::vector<Team>::iterator iter = teams.begin(); iter != teams.end(); ++iter)
{
std::cout << iter->Name << ": " << iter->Value1 << " " iter->Value2 << std::endl;
}
}

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: