I am getting several errors within my code and as I am new to C++ am struggling to figure out what I am doing wrong and what the solution would be. I have googled around a fair bit but nothing I have found has made sense so if anyone can give me some help it would be amazing so that I can learn from this.
The errors are all on line 23 which is search(token);
Error C2672 'search': no matching overloaded function found TakeTwo d:\desktop\twittersearch\taketwo\taketwo\taketwo.cpp 23
Error C2780 '_FwdIt1 std::search(_FwdIt1,_FwdIt1,_FwdIt2,_FwdIt2)': expects 4 arguments - 1 provided TakeTwo d:\desktop\twittersearch\taketwo\taketwo\taketwo.cpp 23
Error C2780 '_FwdIt1 std::search(_FwdIt1,_FwdIt1,_FwdIt2,_FwdIt2,_Pr)': expects 5 arguments - 1 provided TakeTwo d:\desktop\twittersearch\taketwo\taketwo\taketwo.cpp 23
The code:
#include "stdafx.h"
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string token;
int main()
{
int menu_choice;
cout << "Main Menu:\n";
cout << "1. Search for \"winner\" \n";
cout << "Please choose an option: ";
cin >> menu_choice;
if (menu_choice == '1') {
token == "winner";
search(token);
} else {
cout << "\nPlease enter a valid option\n";
system("Pause");
system("cls");
main();
}
return 0;
}
void search(string &token)
{
ifstream fin;
fin.open("sampleTweets.csv");
if (fin.is_open())
{
cout << "File opened successfully" << "\n";
}
else {
cout << "Error opening file" << "\n";
}
string line;
while (getline(fin, line)) {
if (line.find(token) != string::npos) {
int n = line.find(",");
char c;
line[n] = ' '; //Changes the comma spacing
line.erase(remove_if(line.begin(), line.end(), [](char chr) { return chr == '\"' || chr == '\'' || chr == ','; }), //Removes the characters " ' and , from the strings
line.end());
line.erase(n + 1, 1); //Removes the 'b' from the beginning of each tweet
cout << line << endl;
}
}
fin.close();
char anykey;
cout << "press any key";
cin >> anykey;
return;
}
The perils of using namespace std;. Since you never declare or define the search function before it's used, the compiler is assuming you mean std::search which is part of the <algorithm> header. Making sure to declare your function before it's used will fix the error in this case.
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string token;
// Forward declare search before first use
void search(string &token);
int main()
{
int menu_choice;
cout << "Main Menu:\n";
cout << "1. Search for \"winner\" \n";
cout << "Please choose an option: ";
cin >> menu_choice;
if (menu_choice == '1') {
token == "winner";
search(token);
}
else {
cout << "\nPlease enter a valid option\n";
system("Pause");
system("cls");
main();
}
return 0;
}
Related
This is one of my homework and I keep running into seg fault after the cin while loop, can anybody tell what did I do wrong? I have not learn map yet so I can't do that. One of my thought is that it went into seg fault because I was comparing the two string elements inside the vector, what is the way to do that properly?
#include <chrono>
#include <climits>
#include <cfloat>
#include <limits>
#include <cassert>
#include <exception>
#include <cctype>
#include <string>
#include <cmath>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <regex>
#include <vector>
using namespace std;
int main()
{
vector<string> word_input;
vector<int> word_count;
string word;
string fileName;
ifstream inputFile;
cout << "Enter file name: ";
getline(cin,fileName);
inputFile.open(fileName);
while (inputFile.fail())
{
cout << "Can't open the file" << endl;
exit(1);
}
cout << "File opened successfully \n";
while (inputFile >> word)
{
if (word != word_input.back())
{
word_input.push_back(word);
word_count.push_back(1);
}
else
{
word_count.push_back( word_count.back() + 1);
}
}
int count =word_count.back();
// Compare the input words
// and output the times of every word compared only with all the words
for (int i = 0; i != count; ++i)
{
int time = 0;
for (int j = 0; j != count; ++j)
{
if (word_input[i] == word_input[j])
++time;
}
std::cout << "The time of "
<< word_input[i]
<< " is: "
<< time
<< endl;
}
inputFile.close();
return 0;
}
The strategy you are using is fraught with problems. A simpler approach would be to use a std::map<std::string, int>.
int main()
{
std::map<std::string, int> wordCount;
string word;
string fileName;
ifstream inputFile;
cout << "Enter file name: ";
getline(cin,fileName);
inputFile.open(fileName);
if (inputFile.fail())
{
cout << "Can't open the file" << endl;
exit(1);
}
cout << "File opened successfully \n";
while (inputFile >> word)
{
// --------------------------------------------------------------
// This is all you need to keep track of the count of the words
// --------------------------------------------------------------
wordCount[word]++;
}
for ( auto const& item : wordCount )
{
std::cout << "The time of "
<< item.first
<< " is: "
<< item.second
<< std::endl;
}
inputFile.close();
return 0;
}
I am having an issue trying to convert a number into a string. The purpose is for error checking to make sure the number is of a specific length. I have tried using both to_string() and convert.str() functions but get the same error back when trying to compile.
I am using MinGw g++ to compile and realize I need to tell it I want the C++11 standard, which I believe I have done. My compiler code is as follows:
NPP_SAVE
CD $(CURRENT_DIRECTORY)
C:\MinGW\bin\g++ -std=c++11 "$(FULL_CURRENT_PATH)" -o "$(NAME_PART).exe"
cmd /c $(NAME_PART).exe
Now assuming that is correct, my code for using to_string() is as follows:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
int book_code = 0;
cout << "Please enter the four digit book code: ";
cin >> book_code;
string code = to_string(book_code);
while (!(cin >> book_code) || code.length() != 4){
cin.clear();
cin.ignore(10000, '\n');
cout << "That is not a valid code." << endl;
cout << "Please enter the four digit book code: ";
}
}
And my code for using convert.str() is as follows:
int main() {
int book_code = 0;
cout << "Please enter the four digit book code: ";
cin >> book_code;
ostringstream Convert;
convert << book_code;
string code = convert.str();
while (!(cin >> book_code) || code.length() != 4){
cin.clear();
cin.ignore(10000, '\n');
cout << "That is not a valid code." << endl;
cout << "Please enter the four digit book code: ";
}
}
Neither of these was successful and both returned
error: 'to_string' was not declared in this scope
Am I missing something obvious?
In MinGW std::to_string() does not exist, you should declare your own implementation.
std::string to_string(int i)
{
std::stringstream ss;
ss << i;
return ss.str();
}
I recommend you to use MSYS2, it is more actualizated and you can avoid this type of problems.
Edit:
Checking the dot position in double:
#include <iostream>
#include <sstream>
#include <string>
std::string to_str_with_dot_pos(double i, unsigned int &pos)
{
std::stringstream ss;
ss << i;
std::string result(ss.str());
pos = 0;
while (pos < result.length() && result[pos] != '.') {
pos += 1;
}
return result;
}
int main(int argc, char **argv)
{
double d(12.54);
unsigned int pos(0);
// str should be "12.54".
// pos should be 2.
std::string str = to_str_with_dot_pos(d, pos);
std::cout << "double as string: " << str << std::endl;
std::cout << "double dot position: " << pos << std::endl;
return 0;
}
Explanation of the code (the while loop):
It gets every character of the std::string and checks if it does not equals to the . dot character, if the character is not equal to . it will add +1 to the pos variable.
It returns 2 and not 3 because we're counting from 0, not 1.
Also, this question is a duplicate.
Check that your version of MinGw support to_string, as the code above compiles correctly.
I'd recommend a different approach for length checking, one that avoids using strings:
#include <iostream>
#include <cmath>
using namespace std;
int is_len(int number, int len)
{
if(pow(10, len-1) <= number && number < pow(10, len))
return true;
return false;
}
int main()
{
int number = 1000;
cout << is_len(1, 2) << endl;
cout << is_len(1005, 4) << endl;
cout << is_len(9999, 4) << endl;
cout << is_len(599, 4) << endl;
cout << is_len(1005, 5) << endl;
return 0;
}
Prints:
0
1
1
0
0
I have a problem with a function that is having ifstream and string in it.
This my code:
#include <iostream>
#include <time.h>
#include <iomanip>
#include <stdlib.h>
#include <fstream>
#include <string>
const int ArrayMax = 100;
int DisplayMenu();
void LoadNames();
void ReadFile(ifstream& , ifstream& ,string[],string[]);
using namespace std;
int main()
{
ifstream FemaleFile;
ifstream MaleFile;
string Female[ArrayMax];
string Male[ArrayMax];
DisplayMenu();
ReadFile(FemaleFile, MaleFile, Female,Male );
return 0;
}
int DisplayMenu() //Displays menu and returns user selection
{
//variables
int selection;
//Headers
cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << endl;
cout << " Name Guess Game" << endl;
cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << endl;
cout << " Selaect Name Category" << endl;
cout << " 1. Female Names" << endl;
cout << " 2. Male Names" << endl;
cout << " 3. Exit" << endl << endl;
cout << " Enter 1, 2 or 3: " ;
cin >> selection;
while ((selection != 1) && (selection != 2) && (selection != 3) )
{
cout << " Invaild choice, Please Enter 1, 2 or 3: " ;
cin >> selection;
}
return selection;
}
void LoadNames()//Loads name lists from data files into two arrays and returns array sizes. Uses ReadFile(…) function
{
return;
}
void ReadFile(ifstream & FemaleFile ,ifstream & MaleFile, string Female[], string Male[] )//Reads the data of the received file into the received array size and returns the array size.
{
//opening files
FemaleFile.open("female.txt");
MaleFile.open("male.txt");
//Testing files
if (!FemaleFile){
cout << "Error, cannot open this file\n";
return;}
if (!MaleFile){
cout << "Error, cannot open this file\n";
return;}
for (int i=0 ; i < ArrayMax; i++)
{
FemaleFile >> Female[i];
cout << Female[i] << endl;
}
for (int i=0 ; i < ArrayMax; i++)
{
MaleFile >> Female[i];
cout << Male[i] << endl;
}
//closeing files
FemaleFile.close();
MaleFile.close();
return;
}
It is always give me this ERROR:
error C2065: 'ifstream' : undeclared identifier
error C2059: syntax error : ','
error C3861: 'ReadFile': identifier not found
Can you help me with this, please?
I think you put using namespace std; before your functions declaration. I mean add this before int DisplayMenu();. Then it would be OK.
You lost std::ifstream before
using namespace std;
in the function declaration.
I have been beating my head against this code for a few days now. it throws a:
template argument deduction/substitution failed:
error on lines 119, 124,129, 162. (marked with //ERROR HERE )
i am still a super n00b at coding so any help would be appreciated. THANKS IN ADVANCE!!
/*********************
Hangman v2
The classic game of hangman using multiple functions
(from chaper 5 C++ book)
**************************/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cctype>
using namespace std;
//GLOBALS!!
string THE_WORD; //secret word player is tryign to guess
string soFar; //word string ei: "G-ESS"
const int MAX_WRONG = 8; // maximum number of incorrect guesses allowed
char guess; //character guessed by player
int wrong; //incorrect guesses
//Functions used (declarations)
string f_soFar();
void f_used();
int main();
vector<string> used_ch; ///used characters
string getWord()
{
vector<string> words; // collection of possible words to guess
words.push_back("GUESS");
words.push_back("HANGMAN");
words.push_back("DIFFICULT");
words.push_back("ENTERPRISE");
words.push_back("GALAXY");
words.push_back("POMEGRANATE");
words.push_back("CONTROLLER");
srand(static_cast<unsigned int>(time(0))); //Seed based on time
random_shuffle(words.begin(), words.end()); //randomly picks from words vector
string secretWord;
secretWord = words[0]; // word to guess
THE_WORD = secretWord;
cout<<"New Secret word has been chosen!!"<<endl;
cout<<THE_WORD<<endl;
return THE_WORD;
}
void check(char guess)
{
cout << "\n\nEnter your guess:\n\n->";
cin >> guess;
guess = toupper(guess); //make uppercase since secret word in uppercase
while (find (used_ch.begin(), used_ch.end(), guess) != used_ch.end())
{
cout << "\nYou've already guessed " << guess << endl;
cout << "Enter another guess: ";
cin >> guess;
guess = toupper(guess);
if (THE_WORD.find(guess) != string::npos)
{
cout << "That's right! " << guess << " is in the word.\n";
// update used_ch to include newly guessed letter
for (unsigned int i = 0; i < THE_WORD.length(); ++i)
{
if (THE_WORD[i] == guess)
{
used_ch.push_back(&guess);
soFar[i] = guess;
cout<<"Guess again!"<<endl;
}
}
}
else
{
cout << "Sorry, " << &guess << " isn't in the word.\n";
++wrong;
cout<<"Try again!"<<endl;
}
}
}
void f_used()
{
for(unsigned int i = 0; i < used_ch.size(); i++)
{
cout<<used_ch[i]<<", ";
}
}
void replay()
{
char choice;
cout<<"Would you like to play again?\nY/N\n\n->";
cin>>choice;
if(choice == 'Y' || choice == 'y')
{
cout<<"OK!!!! Here we go...."<<endl;
used_ch.clear();
main();
}
else if(choice == 'N' || choice == 'n')
{
cout<<"OK, thanks for playing!!";
}
else //ERROR HERE
{
cout<<"Invalid Entry. please try again...";
replay();
}
} //ERROR HERE
int main()
{
// set-up
getWord(); //ERROR HERE //should get word from word()
//cout<<"The word is "<<THE_WORD<<endl; //TESTING PURPOSES!!
while ((wrong < MAX_WRONG) && (soFar != THE_WORD))
{
//STATUS
cout << "\n\nYou have " << (MAX_WRONG - wrong);
cout << " incorrect guesses left.\n";
cout << "\nYou've used the following letters:\n";
f_used();
cout << "\nSo far, the word is:\n" << soFar << endl;
check(guess);
}
// shut down
if (wrong == MAX_WRONG)
{
cout << "\nYou've been hanged!";
replay();
}
else
{
cout << "\nYou guessed it!";
cout << "\nThe word was " << THE_WORD << endl;
replay();
}
} //ERROR HERE
First, let's look at the full compiler error:
c++ foo.cc -o foo
In file included from foo.cc:7:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/iostream:38:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/ios:216:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__locale:15:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:439:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:846:22: error: invalid operands to binary expression
('std::__1::basic_string<char>' and 'int')
if (*__first == __value_)
~~~~~~~~ ^ ~~~~~~~~
foo.cc:64:12: note: in instantiation of function template specialization 'std::__1::find<std::__1::__wrap_iter<std::__1::basic_string<char> *>, char>' requested here
while (find (used_ch.begin(), used_ch.end(), guess) != used_ch.end())
^
1 error generated.
Now, let's create a reduced test case:
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
std::vector<std::string> used_ch;
char guess = 'c';
find(used_ch.begin(), used_ch.end(), guess);
}
Now, we look at what the problem is:
You're attempting to find a char in a vector of strings. However, there is no overload of operator== that takes a string and a char.
I'm writing a basic random number guessing game, and I'm trying to perfect it a bit when it comes to entering illegal characters, and as long as numbers outside of the range 1-100 are entered the program tells the user and the user gets to redo it, same goes with letters. However, if you enter 23x5 you end up getting double error messages, you get both the letter and a too high/too low depending on the random number. How do I sort it out so that this entry would go under the letter error message as well?
Here's my code:
Header.h
#ifndef HEADER_H
#define HEADER_H
int nGuessedNumber;
int nNumberOfGuesses = 1;
int nRandomNumber;
int UserInput();
#endif
Source.cpp
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
extern int nGuessedNumber;
int UserInput()
{
while(!(cin >> nGuessedNumber))
{
cin.clear();
while(cin.get() != '\n'){}
cout << "I asked for a number between 1 and 100.\n";
}
return nGuessedNumber;
}
main.cpp
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Header.h"
using namespace std;
int main()
{
srand(time(0));
nRandomNumber = rand() % 100 + 1;// sets random number between 1 and 100
cout << "Guess a number from 1 too 100: " << endl;
UserInput();
while (nGuessedNumber != nRandomNumber)
{
if ((nGuessedNumber < 1) || (nGuessedNumber > 100))
{
cout << "Oi! Between 1 and 100!\n";
UserInput();
}
else
{
if (nGuessedNumber < nRandomNumber)
{
for (nGuessedNumber; nGuessedNumber < nRandomNumber; nNumberOfGuesses++)
{
cout << "Too low, try again!" <<endl;
UserInput();
}
}
else if (nGuessedNumber > nRandomNumber)
{
for (nGuessedNumber; nGuessedNumber > nRandomNumber; nNumberOfGuesses++)
{
cout << "Too high, try again!"<< endl;
UserInput();
}
}
}
}
if (nGuessedNumber == nRandomNumber)
{
cout << "Congratulations! " << nGuessedNumber << " is correct!" << endl;
cout << "You guessed " << nNumberOfGuesses << " times." << endl;
}
system("PAUSE");
return 0;
}
Read whole lines from std::cin and parse them individually using std::istringstream:
int UserInput()
{
std::string line;
while (getline(std::cin, line)) {
std::istringstream is(line);
if (is >> nGuessedNumber) {
...
return nGuessedNumber;
} else {
...
}
}
}