Im a beginner to C++. Its my first year in college. Im completely stuck at this.I have to make a program which takes input 4 strings then check if some value already exists if it does then output value exists and thats it, if not, if they all are unique(all 4 strings) then output them in ascending order.Code bellow works and it already outputs them in ascending order, but how to find if values repeats before writing them?
sorry for my bad English guys i hope u understand what I am trying to say here
string name[4];
string temp;
for(int i=0;i<4;i++){
cout<<"Enter "<<i+1<<" string"<<endl;
getline(cin,name[i]);
}
for(int i=0;i<4;i++){
for(int j=i+1;j<4;j++){
if(name[i]>name[j]){
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for(int i=0; i<4; i++){
cout<<name[i]<< " ";
}
You could use the string comparison to check it before pushing it. This is if you want to check that the string is unique, not if you have shared words within each string (which is slightly more complicated.
string name[4];
string temp;
for(int i=0;i<4;i++)
{
cout<<"Enter "<<i+1<<" string"<<endl;
getline(cin,name[i]);
}
int failed = 0;
for(int i = 0;i<4;i++)
{
for(int j=0;j<i;j++)
{
// Check if the string is the same as any previous strings.
if (name[i].compare(name[j]) != 0)
{
failed = 1;
cout<<"String exists multiple times: "<<name[i];
}
}
}
// Check if there were any shared strings
if(failed==0)
{
for(int i=0; i<4; i++)
{
cout<<name[i]<< " ";
}
}
Reference:
http://www.cplusplus.com/reference/string/string/compare/
So the best way is going to be to use a better container!
Lets have a look at a std::set here.
std::set is an associative container that contains a sorted set of
unique objects.
So how can we best use this, there are many examples, but we can look at your particular one.
#include <set> // For Set
int main() {
set<string> names; // our fun easy ordered set.
string name; // a name to read in
unsigned int nameCounter = 0; // a counter
// loop until we have 4 correct names.
while (nameCounter < 4) {
cout<<"Enter "<<nameCounter+1<<" name"<<endl;
getline(cin,name);
// Check that when they enter it into the set that it is actually inserted.
// Here we are being clever because "insert" returns a tuple with a bool
// to tell us if we put it in correctly.
if (!names.insert(name).second) {
cout << "That was not unique!" << endl;
} else {
nameCounter++;
}
}
// Now we can loop through the names which is already sorted for us!
for (auto listName : names) {
cout << listName << " ";
}
cout << endl;
}
Wasn't that easy!? It is almost always better to utilize the std library than do things your self!
Here is a live example.
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if((name[i]==name[j]) && (i!=j)){
cout<<"already exits";
}
Related
I have an array and I want to subtract each of the elements consecutively, ex: {1,2,3,4,5}, and it will result to -13 which is by 1-2-3-4-5.
But I don't declare or make those numbers fixed as they're taken from the input (user). I only make it like, int array[100] to declare the size.
Then, to get the inputs, I use the for loop and insert them to the array. Let's say first input is 10, then array[0] must be 10 and so on.
The problem is, how do I subtract them? I have two options:
The first element of the array (array[0]) will subtract the next element (array[1]) right after the user input the second element, and the result (let's say it's int x) will subtract the next element (array[2]) after the user input it and so on.
I'll have the user input all the numbers first, then subtract them one by one automatically using a loop (or any idea?) *These elements thing refer to the numbers the user input.
Question: How do you solve this problem?
(This program will let the user input for as much as they want until they type count. Frankly speaking, yeah I know it's quite absurd to see one typing words in the middle of inputting numbers, but in this case, just how can you do it?)
Thanks.
Let's see my code below of how I insert the user input into the array.
string input[100];
int arrayInput[100];
int x = 0;
for (int i = 0; i >= 0; i++) //which this will run until the user input 'count'
{
cout << "Number " << i+1 << ": ";
cin >> input[i];
arrayInput[i] = atoi(input[i].c_str());
...
//code to subtract them, and final answer will be in int x
...
if (input[i] == "count")
{
cout << "Result: " << x << endl;
}
}
You can/should use a dynamic sized container like std::vector as shown below:
#include <iostream>
#include <vector>
int main()
{
int n = 0;
//ask user how many input he/she wants to give
std::cout << "How many elements do you want to enter: ";
std::cin >> n;
std::vector<int> vec(n); //create a vector of size n
int resultOfSubtraction = 0;
//take input from user
for(int i = 0 ; i < n ; ++i)
{
std::cin >> vec.at(i);
if(i != 0)
{
resultOfSubtraction-= vec.at(i);
}
else
{
resultOfSubtraction = vec.at(i);
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}
Execute the program here.
If you want a string to end the loop then you can use:
#include <iostream>
#include <vector>
#include <sstream>
int main()
{
std::vector<int> vec;
int resultOfSubtraction = 0, i = 0;
std::string endLoopString = "count";
std::string inputString;
int number = 0;
//take input from user
while((std::getline(std::cin, inputString)) && (inputString!=endLoopString))
{
std::istringstream ss(inputString);
if(ss >> number)
{
vec.push_back(number);
if(i == 0)
{
resultOfSubtraction = number;
}
else
{
resultOfSubtraction-= number;
}
++i;
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}
I am trying to write a contact list program in the C++ programming language and I think I have a good base set up for one. The premise of the program is that two vectors of values are entered. One vector for the contact name and another for the phone number. Once a few of these values are taken in by the program, a single contact name is supposed to signify to the program that its corresponding phone number should be outputted.
(Note: The '3' is supposed to tell the program how many values are to be stored in each vector. In this case, it is 3 contact names and 3 phone numbers.)
Ex. Input: 3 Joe 123-5432 Linda 983-4123 Frank 867-5309 Frank
Ex. Output: 867-5309
But I am getting an error message that reads, "Exited with return code -11 (SIGSEGV)." I'm not sure where I could be leaking any memory but maybe I just can't see it.
Any help that can fix this error would be greatly appreciated.
Below is code that I have written so far:
#include <iostream>
#include <vector>
using namespace std;
string GetPhoneNumber(vector<string> nameVec, vector<string> phoneNumberVec, string contactName) {
string theName;
string thePhoneNum;
string theContName;
int N;
int nElements;
cin >> N;
cin >> theName;
cin >> thePhoneNum;
cin >> theName;
cin >> thePhoneNum;
cin >> theName;
cin >> thePhoneNum;
nameVec.push_back(theName);
phoneNumberVec.push_back(thePhoneNum);
cin >> contactName;
nElements = phoneNumberVec.size();
for (int i = 0; i < nElements; i++) {
if (i == N) {
return phoneNumberVec.at(i);
}
}
}
int main() {
vector<string> nameVec;
vector<string> phoneNumberVec;
string contactName;
cout << GetPhoneNumber(nameVec, phoneNumberVec, contactName) << endl;
return 0;
}
The issue is that you are supposed to return a std::string from GetPhoneNumber, but there are code paths where no return is specified.
What happens is that the program has now invoked undefined behavior, as returning no value from a function that's supposed to return a value leads to undefined behavior occurring.
The fix is to return a std::string from the GetPhoneNumber function from all code paths. Namely right here:
for (int i = 0; i < nElements; i++) {
if (i == N) {
return phoneNumberVec.at(i);
}
}
return ""; // or some appropriate string.
}
To prove that this is the issue, if you do not have that return statement, and instead did this:
for (int i = 0; i < nElements; i++) {
if (i == N) {
return phoneNumberVec.at(i);
}
}
std::cout << "There will be a problem" << std::endl;
}
You will see the string,
There will be a problem
outputted, proving you are reaching that point in the function without returning a value.
Here is a live example.
The other issue is that i could never equal N, since a std::vector uses 0-based indexing. If N is 1, then the highest index for i will be 0.
The fix is to compare i to N-1.
My task is to create a program to ensure that unauthorized users cannot get into the system. (This is just a scenario, not the real thing). I was given a text file with 300 numbers on it. The user has to type in the number, if it is not included in the text file access will be denied. If it is included in the text file, access will be granted. The rest will be shown below.
So far this is what I have done
#include <iostream>
#include <fstream>
using namespace std;
bool mySequentialSearch(int data[300], int key, int size)
{
for(int i=0; i<size; i++)
{
if (data[i] == key)
return true;
}
return false;
}
int main()
{
int codes;
string line;
ifstream fin ("SystemAccessCodes.txt");
while (fin>>codes)
{
for(int i=0; i<3; i++)
{
cout<<"\nAttempt "<< i+1 << "/3 : ENTER 4 DIGIT CODE: ";
int ans;
cin>>ans;
if(mySequentialSearch(&codes, ans, 300))
{
cout<<"===================="<<endl;
cout<<" Access Granted "<<endl;
cout<<" Welcome "<<endl;
cout<<"===================="<<endl;
system ("pause");
return 0;
}
else
{
cout<<"\nNot matching! Try Again"<<endl;
}
fin.close();
}
}
system ("pause");
return 0;
}
My problem is I don't know how to use the textfile as an array. And it only reads the first number of the file.
Here is some of the numbers in the file (1450
1452
1454
1456
1458
1460) and the program I built only reads 1450.
Separate reading the codes and checking the user input. It makes no sense to do all that in a single loop.
int codes[300];
for(int i = 0; i < 300 && fin; ++i) {
fin>>codes[i];
}
fin.close();
for(int i=0; i<3; i++)
{
cout<<"\nAttempt "<< i+1 << "/3 : ENTER 4 DIGIT CODE: ";
int ans;
cin>>ans;
if(mySequentialSearch(codes, ans, 300))
{
cout<<"===================="<<endl;
cout<<" Access Granted "<<endl;
cout<<" Welcome "<<endl;
cout<<"===================="<<endl;
system ("pause");
return 0;
}
else
{
cout<<"\nNot matching! Try Again"<<endl;
}
}
The better way in c++ is to use a std::vector<int> instead of the raw array though:
std::vector<int> codes;
int code;
while(fin>>code) {
codes.push_back(code);
}
Instead of your mySequentialSearch() function, you can simply use std::vector::find() then.
Here you go:
I think it would be good to use an unordered_set here. To get that, make sure you use #include <unordered_set>
int codes;
std::string line;
std::ifstream fin("SystemAccessCodes.txt");
//lets use a set.
//Sets cannot contain duplicates. If the number is in the set, it is a valid code.
//it might be a better option to use strings rather than ints as passwords
//(large numbers could cause problems)
std::unordered_set<int> codeset;
//populate the set
while (fin >> codes)
{
codeset.insert(codes);
}
fin.close();
//now run this iteration
for (int i = 0; i < 3; i++)
{
std::cout << "\nAttempt " << i + 1 << "/3 : ENTER 4 DIGIT CODE: ";
int ans;
std::cin >> ans;
//count returns either 0 or 1: 0 if the ans is not in it, 1 if it is
if(codeset.count(ans))
{
std::cout << "====================\n";
std::cout << " Access Granted \n";
std::cout << " Welcome \n";
std::cout << "====================\n";
system("pause");
return 0;
}
else
{
std::cout << "\nNot matching! Try Again" << std::endl;
}
}
system("pause");
return 0;
Notes:
Using "using namespace std" pollutes the global namespace. I prefer to use "std::"
Your mySequentialSearch causes an n^2 runtime of your program. Using sets cuts it down to n (linear).
For more information on sets: http://en.cppreference.com/w/cpp/container/unordered_set
For more information on ifstream: http://en.cppreference.com/w/cpp/io/basic_ifstream
It would probably be a good idea to add some error checking (file doesn't exist, bad input, etc.)
I am trying to work on a assignment which need to input two string S & str and then deliver three results (Without using any string library):
1.Determine the number and positions of the given str in S
2.Return S with any possible occurrence of str removed
ex. if S=aababacd cdefgh ,
str=aba
The Frequency is 2, position is <0,2>
The Character Delete would be cd cdefgh
Attached code is what I have done so far, I can output the Frequency and the position, but now I have few unsolved questions and I have no idea how to implement it.
1.Once I input a string with space in there, ex. abcd efg, the code will implement it immediately, it will not consider abcd efg as one string but consider it as S=abcd and str=efg , with this problem I cant input a string with blank space to test.
2.How can I output the position like this form: <0,2> , because I am using a loop to output the result so it cant not be like that, I was thinking whether I can create an array to store i and then cout it, but I failed.
3.About the character Delete problem, I found one similar problem, it said if I know how to use strcpy without using library then I would know, but I learned it and I still dont know how to handle this question, I know I can compare these two strings but I dont know how to output S without the str part.I was thinking to change the S into '\0' after loop and output it, but that was totally wrong.
I would be really appreciated if anyone could give me some advice, thank you!
#include <iostream>
#include <algorithm>
using namespace std;
void CharacterDelete(){
char S[100], str[100];
bool match =true;
cout << "Enter string S :";
cin >> S;
cout << "Enter string str :";
cin>>str;
for(int i=0; S[i]!='\0'; i++)
{
for(int j=0; str[j]!='\0';j++){
if(S[i+j]!=str[j]){
match=false;
break;
}
if(match){
S[i+j]='\0';
}
}
}
cout<<S;//Apparently thats a wrong solution
}
void Frequency(){
string S,str;
cout<<"Please input string S"<<endl;
cin>>S;
cout<<"Please input string str"<<endl;
cin>>str;
int sum=0;
for (int i=0; i<S.size(); i++)
{
if (i + str.size() > S.size()) break;
bool match=true;
for (int j=0; j<str.size(); j++)
if (S[i+j] != str[j])
{
match=false;
break;
//Once we print blank space and it would implement it immediately?
}
if(match)
{
sum++;
cout<<"Start from"<<i<<endl;
//What if we use an array to store it and then output it?but how to write it?
}
}
cout<<"The Frequency is "<<sum<<endl;
if(sum==0){
cout<<"There is no starting point"<<endl;
}
}
int main() {
Frequency();
CharacterDelete();
return 0;
}
You are using local variables S and str. You need to use S and str in main function. Then transfer this variables from main in Frequency() and CharacterDelete.
Delete characters: create new variable then copy there characters without delete-characters.
Output:
cout << "<" << num_word << ", " << number << ">\n";
Here is the assignment:
Write a program that reads in a text file one word at a time. Store a word into a dynamically created array when it is first encountered. Create a paralle integer array to hold a count of the number of times that each particular word appears in the text file. If the word appears in the text file multiple times, do not add it into your dynamic array, but make sure to increment the corresponding word frequency counter in the parallel integer array. Remove any trailing punctuation from all words before doing any comparisons.
Create and use the following text file containing a quote from Bill Cosby to test your program.
I don't know the key to success, but the key to failure is trying to please everybody.
At the end of your program, generate a report that prints the contents of your two arrays in a format similar to the following:
Word Frequency Analysis
I 1
don't 1
know 1
the 2
key 2
...
Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int readInFile (string tempArray [], string file, int arraySize);
int main()
{
ifstream inputFile;
string *readInArray = 0,
*compareArray = 0,
filename,
word;
int wordCount = 0;
int encountered = 0;
int j = 0,
*wordFrequency = 0;
cout << "Enter the filename you wish to read in: ";
getline(cin, filename);
inputFile.open(filename.c_str());
if (inputFile)
{
while (inputFile >> word)
{
wordCount++;
}
inputFile.close();
readInArray = new string[wordCount];
readInFile(readInArray, filename, wordCount);
}
else
{
cout << "Could not open file, ending program";
return 0;
}
compareArray = new string[wordCount];
wordFrequency = new int[wordCount];
for (int count = 0; count < wordCount; count++)
wordFrequency[count] = 0;
for(int i = 0; i < wordCount; ++i)
{
j = 0;
encountered = 0;
do
{
if (readInArray[i] == compareArray[j])
encountered = 1;
++j;
} while (j < wordCount);
if (encountered == 0)
{
compareArray[i]=readInArray[i];
wordFrequency[i] += 1;
}
}
for(int k=0; k < wordCount; ++k)
{
cout << "\n" << compareArray[k] << " ";
}
for(int l=0; l < wordCount; ++l)
{
cout << "\n" << wordFrequency[l] << " ";
}
return 0;
}
int readInFile (string tempArray [], string file, int arraySize)
{
ifstream inputFile;
inputFile.open(file.c_str());
if (inputFile)
{
cout << "\nHere is the text file:\n\n";
for(int i=0; i < arraySize; ++i)
{
inputFile >> tempArray[i];
cout << tempArray[i] << " ";
}
inputFile.close();
}
}
Here is my question:
How do you store a word into a dynamically created array when it is first encountered? As you can see from my code made a string array with some of the elements empty. I believe it is suppose to be done using pointers.
Also how do I get rid of the punctuation in the string array? Should it be converted to a c-string first? But then how would I compare the words without converting back to a string array?
Here is a link to a java program that does something similar:
http://math.hws.edu/eck/cs124/javanotes3/c10/ex-10-1-answer.html
Thank you for any help you can offer!!
As to the first part of your question, you are not using a dynamically created array. You are using a regular array. C++ provides implementations of dymnamic arrays, like the vector class http://www.cplusplus.com/reference/vector/vector/
As to the second part of your question, I see no reason to convert it to a c string. The string class in c++ provides functionality for removing and searching for characters. http://www.cplusplus.com/reference/string/string/
The string::erase function can be used to erase punctuation characters found with string::find.
Note: There are other ways of doing this assignment that may be easier (like having an array of structs containing a string and an int, or using a map) but that may defeat the purpose of the assignment.