I want to search thorough a vector to see if an element appears. Once this element appears along with others, i want to re-search through the original to see if this second element appears else where within the vector. The end result should show the first element being found and then the information of where the second element appears.
void searchband()
{
ifstream artist("newartist.txt");
string SBand;
cout << "Please enter the band you want to seach" << endl;
cin >> SBand;
system("CLS");
while (artist >> forname >> surname >> bandnum)
{
band.clear();
for (int i = 0; i < bandnum; i++)
{
string tmp;
artist >> tmp;
band.push_back(tmp);
}
artist >> role;
if (find(band.begin(), band.end(), SBand) != band.end())
{
cout << forname << " " << surname << endl;
cout << "Played for: ";
ostream_iterator<string> output_iterator(cout, " ");
copy(band.begin(), band.end(), output_iterator);
cout << " " << endl;
cout << " " << endl;
newband = band;
}
if (find(band.begin(), band.end(), newband) != band.end())
{
cout << forname << " " << surname << endl;
cout << "Played for: ";
ostream_iterator<string> output_iterator(cout, " ");
copy(band.begin(), band.end(), output_iterator);
cout << " " << endl;
cout << " " << endl;
}
system("pause");
cin.get();
main();
}
}
This gets the error code
error C2678: binary '==' : no operator found which takes a left-hand operand of type std::basic_string<char,std::char_traits<char>,std::allocator<char>> (or there is no acceptable conversion)
I think it may be because
vector<string> = newband
but that is the only way i can think of to pass the vector information over is to another vector
std::find_first_of does what you are looking for:
Searches the range [first, last) for any of the elements in the range [s_first, s_last).
Example (also taken from cppreference):
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v{0, 2, 3, 25, 5};
std::vector<int> t{3, 19, 10, 2};
auto result = std::find_first_of(v.begin(), v.end(), t.begin(), t.end());
if (result == v.end()) {
std::cout << "no elements of v were equal to 3, 19, 10 or 2\n";
} else {
std::cout << "found a match at "
<< std::distance(v.begin(), result) << "\n";
}
}
Related
I'm trying to prompt the user for items and the quantity of those items respectively. But when I run the program, it correctly displays the elements in the first vector, and not the elements in the second vector.
#include <iostream>
#include <vector>
using namespace std;
int main(){
// Declaring vectors
vector <string> items{};
vector <int> quantity{};
cout << "Enter name of items." << endl;
// Read input to vectors
for(int i{1}; i <= 3; ++i){
string item{};
cin >> item;
items.push_back(item);
}
cout << "Enter quantity of each item." << endl;
for(int i{1}; i <= 3; ++i){
int num{};
cin >> num;
quantity.push_back(num);
}
// Display data
for(auto item: items){
int i{0};
cout << "Item: " << item << " - " << "Quantity: " << quantity.at(i) << endl;
++i;
cout << "--------------------" << endl;
}
return 0;
}
output
Enter name of items.
meat fish milk
Enter quantity of each item.
10 20 30
Item: meat - Quantity: 10
--------------------
Item: fish - Quantity: 10
--------------------
Item: milk - Quantity: 10
--------------------
I tried printing out quantity.at(1) and it correctly displays 20, I apologize in advance if I missed out on something obvious. I'm very new to the language.
You are always setting i equal to the 0th element. instead move the creation of i to be outside the loop:
int i{0};
for(auto item: items){
cout << "Item: " << item << " - " << "Quantity: " << quantity.at(i) << endl;
++i;
cout << "--------------------" << endl;
}
You can fix it by bringing the "i" variable out of the last iteration
I am brushing up some skills on C++ STL and I wrote a basic insertion/deletion code for maps.
Below is the code.
It is taking some inputs from user and inserting/deleting accordingly.
Very simple code.
But the issue is I have to write separate print functions for every map variant.
Is there anything I can do to make it common as we do in templates?
Any help would be highly appreciated.
#include <iostream>
#include <map>
#include <unordered_map>
using namespace std;
void print(const map<int, string>& mp)
{
cout << "Contents of map: { ";
for(auto& it: mp)
{
cout << it.first << " -> " << it.second << " ";
}
cout << "}" << endl;
}
void print(const multimap<int, string>& mp)
{
cout << "Contents of multi map: { ";
for(auto& it: mp)
{
cout << it.first << " -> " << it.second << " ";
}
cout << "}" << endl;
}
void print(const unordered_map<int, string>& mp)
{
cout << "Contents of unordered map: { ";
for(auto& it: mp)
{
cout << it.first << " -> " << it.second << " ";
}
cout << "}" << endl;
}
void print(const unordered_multimap<int, string>& mp)
{
cout << "Contents of unordered multi map: { ";
for(auto& it: mp)
{
cout << it.first << " -> " << it.second << " ";
}
cout << "}" << endl;
}
int main()
{
map<int, string> mp1;
multimap<int, string> mp2;
unordered_map<int, string> mp3;
unordered_multimap<int, string> mp4;
int value = 0;
string str;
cout << "Inserting..." << endl;
while(value >= 0)
{
cout << "Enter number: ";
cin >> value;
if(value >= 0)
{
cout << "Enter string: ";
cin >> str;
mp1.insert(pair<int, string>(value, str));
mp2.insert(pair<int, string>(value, str));
mp3.insert(pair<int, string>(value, str));
mp4.insert(pair<int, string>(value, str));
}
}
print(mp1);
print(mp2);
print(mp3);
print(mp4);
value = 0;
cout << "Removing..." << endl;
while(value >= 0)
{
cout << "Enter number: ";
cin >> value;
if(value >= 0)
{
// removing by value
mp1.erase(value);
mp2.erase(value);
mp3.erase(value);
mp4.erase(value);
}
}
print(mp1);
print(mp2);
print(mp3);
print(mp4);
return 0;
}
Well, yes, that is, indeed, what templates are used for, right?
template<typename T>
void print(const T& mp)
{
cout << "Contents of map: { ";
for(auto& it: mp)
{
cout << it.first << " -> " << it.second << " ";
}
cout << "}" << endl;
}
This'll work as long as only maps, or reasonable facsimiles thereof, are passed to print() (and both keys and values in the maps have a working << overload). Otherwise, it might become necessary to use SFINAE or C++20 concepts to constrain overload resolution.
1 : http://itweb.fvtc.edu/ag/?u=3&f=cpp-assignment3
I am to swap the integer using a SwapInteger function outside the main function type using pointer. The user input a number and then the computer will compile and change the result to the given result that our professor have assigned.
I've tried creating a void swapInteger function and input some code in to see if that swap the code but that does nothing. So i just added some code into the main function but I don't think that's what our professor wanted us to do. He did stated "do not modify the main function"
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
// TODO: Implement the "SwapIntegers" function
void swapIntegers(int *first, int *second)
{
int *pSwapIntegers = first;
first = second;
second = pSwapIntegers;
}
// Do not modify the main function!
int main()
{
int first = 0;
int second = 0;
int *pFirst = new int (first);
int *pSecond = new int (second);
cout << "Enter the first integer: ";
cin >> first;
cout << "Enter the second integer: ";
cin >> second;
cout << "\nYou entered:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
swapIntegers(&first, &second);
cout << "\nAfter swapping:\n";
cout << "first: " << *pFirst << "\n";
cout << "second: " << *pSecond << "\n";
cout << "\nPress any key to quit.";
_getch();
return 0;
}
I expected the computer to compile the two integer that the user input and then show the swapped integer to the user. Please take a look at my code if you have questions
Inside of your swapIntegers(), you are swapping the pointers themselves, not the values of the variables they are pointing at. The caller's variables are not being updated.
swapIntegers() needs to look more like this instead:
void swapIntegers(int *first, int *second)
{
int saved = *first;
*first = *second;
*second = saved;
}
Also, your main() is buggy. It dynamically allocates 2 int variables that it leaks and never assigns the user's input values to. The final "After swapping" output is printing out values from those pointers, not from the variables that were actually swapped. The code will NOT display the expected output. So, despite what the instructions say, main() NEEDS to be modified in order to operate properly, and if your professor has a problem with that, tough. He made a mistake in the code he gave you.
main() should look more like this:
int main()
{
int first = 0;
int second = 0;
cout << "Enter the first integer: ";
cin >> first;
cout << "Enter the second integer: ";
cin >> second;
cout << "\nYou entered:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
swapIntegers(&first, &second);
cout << "\nAfter swapping:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
cout << "\nPress any key to quit.";
_getch();
return 0;
}
Or, like this:
// Do not modify the main function!
int main()
{
int first = 0;
int second = 0;
int *pFirst = &first;
int *pSecond = &second;
cout << "Enter the first integer: ";
cin >> first;
cout << "Enter the second integer: ";
cin >> second;
cout << "\nYou entered:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
swapIntegers(&first, &second);
cout << "\nAfter swapping:\n";
cout << "first: " << *pFirst << "\n";
cout << "second: " << *pSecond << "\n";
cout << "\nPress any key to quit.";
_getch();
return 0;
}
Or, like this:
int main()
{
int *pFirst = new int (0);
int *pSecond = new int (0);
cout << "Enter the first integer: ";
cin >> *pFirst;
cout << "Enter the second integer: ";
cin >> *pSecond;
cout << "\nYou entered:\n";
cout << "first: " << *pFirst << "\n";
cout << "second: " << *pSecond << "\n";
swapIntegers(pFirst, pSecond);
cout << "\nAfter swapping:\n";
cout << "first: " << *pFirst << "\n";
cout << "second: " << *pSecond << "\n";
delete pFirst;
delete pSecond;
cout << "\nPress any key to quit.";
_getch();
return 0;
}
UPDATE: oh wait, it is not your professor's fault, it is YOUR fault. The main() you have presented here DOES NOT match the main() given in the actual assignment!. This is what the original main() looks like:
// Do not modify the main function!
int main()
{
int first = 0;
int second = 0;
cout << "Enter the first integer: ";
cin >> first;
cout << "Enter the second integer: ";
cin >> second;
cout << "\nYou entered:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
SwapIntegers(&first, &second);
cout << "\nAfter swapping:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
cout << "\nPress any key to quit.";
_getch();
return 0;
}
This code is correct. So YOU are the one who introduced the bad use of pointers in main(). So just revert back to the original main() code you were given. And then implement swapIntegers() properly. As the instructions told you to do.
How do I direct the output of this code into a .txt file?
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
int main() {
using std::cin;
using std::cout;
using std::endl;
int input=1;
int sum=0;
int counter=1;
while (input != 0)
{
std::cout << "Please enter the hit data: ";
std::cin >> input;
if (input == 0) // after puting in data input zero
{
break;
}
else if (input != 0)
{
sum += input;
counter++;
}
}
counter = counter - 1 ;
std::cout << "Sum of hits entered: " << sum << endl ;
std::cout << "Number of hits entered: " << counter << endl ;
if ( counter < 100 )
{
std::cout << "The hits are less than 100" ;
}
else if ( counter > 100 )
{
std::cout << "The hits are greater than 100" ;
}
else if ( counter == 100 )
{
std::cout << "The hits are equal to 100" ;
}
}
Also, instead of a user having to input data, how can I get the program to read data from another .txt file? I understand you can do this all easily in the terminal; however, I would like for the program to create the .txt file.
Also, how do I get the program to recognize certain numbers? I want it to output something like "there was twelve number -11s counted".
Use std::ifstream to read input from a file, and std::ofstream to write output to a file. For example:
#include <iostream>
#include <fstream>
int main()
{
int sum = 0;
int counter = 0;
std::ifstream in("hits.txt");
if (in.is_open())
{
while (in >> input)
{
sum += input;
++counter;
}
}
else
{
std::ofstream out("hits.txt");
int input;
do
{
std::cout << "Please enter the hit data: ";
// after putting in data, input zero
if (!(std::cin >> input) || (input == 0))
break;
out << input << " ";
sum += input;
++counter;
}
while (true);
}
std::cout << "Sum of hits entered: " << sum << endl ;
std::cout << "Number of hits entered: " << counter << endl ;
if (counter < 100)
{
std::cout << "The hits are less than 100" << std::endl;
}
else if (counter > 100)
{
std::cout << "The hits are greater than 100" << std::endl;
}
else
{
std::cout << "The hits are equal to 100" << std::endl;
}
return 0;
}
Also, how do I get the program to recognize certain numbers? I want it to output something like "there was twelve number -11s counted".
You can use std:map for that, eg:
#include <iostream>
#include <fstream>
#include <map>
int main()
{
int sum = 0;
int counter = 0;
std::map<int, int> hits; // hit counter
std::ifstream in("hits.txt");
if (in.is_open())
{
while (in >> input)
{
hits[input]++;
sum += input;
++counter;
}
}
else
{
std::ofstream out("hits.txt");
int input;
do
{
std::cout << "Please enter the hit data: ";
// after putting in data, input zero
if (!(std::cin >> input) || (input == 0))
break;
out << input << " ";
hits[input]++;
sum += input;
++counter;
}
while (true);
}
std::cout << "Sum of hits entered: " << sum << endl ;
std::cout << "Number of hits entered: " << counter << endl ;
if (counter < 100)
{
std::cout << "The hits are less than 100" << std::endl;
}
else if (counter > 100)
{
std::cout << "The hits are greater than 100" << std::endl;
}
else
{
std::cout << "The hits are equal to 100" << std::endl;
}
for (auto &p : hits)
{
if (p.second == 1)
std::cout << "there was 1 number " << p.first << " counted" << std:::endl;
else
std::cout << "there were " << p.second << " number " << p.first << "'s counted" << std:::endl;
}
/* or, if you are not using C++11 or later:
for (std::map<int, int>::iterator iter = hits.begin(); iter != hits.end(); ++iter)
{
std::map<int, int>::value_type &p = *iter;
if (p.second == 1)
std::cout << "there was 1 number " << p.first << " counted" << std:::endl;
else
std::cout << "there were " << p.second << " number " << p.first << "'s counted" << std:::endl;
}
*/
return 0;
}
Outputting data to a .txt file is easy indeed. You already included , now you need to create an object from the type std::ofstream and use it to write your text into a file. I would create a function like this (above main):
#include <iostream>
#include <fstream>
#include <string>
void outputTextToFile (std::string p_text) {
//is created under your project filepath:
std::ofstream file("nameoffile.txt", std::ios::app); //"app" = appending, instead of overwriting text
file << "Writing this to a file.\n";
file.close();
}
Afterwards you can call your function in the while loop with the string text you want, like this for example:
outputTextToFile("test Text");
Reading text from a .txt file is very similar to this, I would suggest you look up this thread: Read file line by line
Here is my code, I have attached the screenshot of what output Zybooks expects, and what my output is. I am trying to get it to output exactly what Zybooks is asking, however something seams to be wrong. It is compiling though. Or maybe Zybooks is just being stupid?
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include <cstring>
using namespace std;
int main() {
string title;
string col1;
string col2;
string val;
int numCommas = 0;
vector<string> stringData;
vector<int> intData;
cout << "Enter a title for the data:" << endl;
getline(cin, title);
cout << "You entered: " << title << endl << endl;
cout << "Enter the column 1 header:" << endl;
getline(cin, col1);
cout << "You entered: " << col1 << endl << endl;
cout << "Enter the column 2 header:" << endl;
getline(cin, col2);
cout << "You entered: " << col2 << endl << endl;
while (1) {
cout << "Enter a data point (-1 to stop input):" << endl;
getline(cin, val);
if (val == "-1") {
break;
}
if (val.find(',') == -1) {
cout << "Error: No comma in string." << endl << endl;
}
else {
for (int i = 0; i < val.length(); i++) {
if (val.at(i) == ',') {
numCommas++;
if (numCommas > 1){
break;
}
}
}
if (numCommas == 1) {
stringData.push_back(val.substr(0, val.find(',')));
intData.push_back(stoi(val.substr(val.find(',') + 1, val.length() - 1)));
cout << "Data string: " << val.substr(0, val.find(',')) << endl;
cout << "Data integer: " << stoi(val.substr(val.find(',') + 1, val.length() - 1)) << endl;
}
else {
cout << "Error: Too many commas in input." << endl << endl;
}
}
}
return 0;
}
Thanks.
Thanks.
Your problem is that you initialise numCommas to zero at the start of the program rather than at the start of each author input. That means, once it exceeds one, it will stay that high at least(a), meaning future inputs will always be seen as having too many commas.
You just need to set it to zero immediately before checking each input.
(a) Well, until it wraps around (if it wraps around). But that will be an awful lot of commas you need to input :-)