Working with vectors C++ [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Complicated question, probably simple answer. So the program I need to make cannot include any library other than String, iostream, and vector. I need to create a program that has 3 functions. One that creates an integer vector, one that reverses a vector, and one that prints a vector. In order to take in values I need to use getline to intake a string, if the string states quit, we stop putting new values into it. Other wise we need to test if its an integer(positive or negative) and add it to the vector. My code is starting to get complicated so I really need some help. Below is what i have so far. I'm also using Visual Studio, if that matters. Thanks for any help in advance! The question I have is when I run the program, it will only output the first digit. I don't know why and would like to know what I'm doing wrong.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> CreateVector()
{
string tempvariable;
bool quit = false;
vector<int> userinput;
cout << "Please enter in an integer, type 'quit' to exit " << endl;
while (!quit)
{
getline(cin, tempvariable);
if (tempvariable == "quit")
quit = true;
else
{
bool isaninteger = true;
for(int i = 1; i <= tempvariable.size(); i++)
{
if (tempvariable[i] = "-" || isdigit(tempvariable[i]))
continue;
else
{
cout << "You entered in an incorrect option, please enter in a correct option" << endl;
cin.clear();
cin.ignore();
isaninteger = false;
break;
}
}
if (isaninteger)
userinput.push_back(stoi(tempvariable));
cout << "Please enter in an integer, type 'quit' to exit " << endl;
}
}
return userinput;
}
void printVector(vector<int> userinput)
{
int amountofspots = userinput.size();
cout << "Your Vector is ";
for (int i = 0; i < amountofspots; i++)
{
if (i = (amountofspots - 1))
cout << userinput.at(i) << endl;
else
cout << userinput.at(i) << " , ";
}
}
void reverseVector(vector<int>& userinput)
{
int amountofspots = userinput.size();
vector<int> tempvector;
for (int i = 0; i < amountofspots; i++)
tempvector.push_back(userinput.at(amountofspots - i));
for (int i = 0; i < amountofspots; i++)
userinput.pop_back();
for (int i = 0; i < amountofspots; i++)
userinput.push_back(tempvector.at(i));
}
int main()
{
vector<int> CreatedVector = CreateVector();
printVector(CreatedVector);
reverseVector(CreatedVector);
printVector(CreatedVector);
system("pause");
return 0;
}

Change if (i = (amountofspots - 1)) to if (i == (amountofspots - 1)) in the loop in printVector().
Change tempvariable[i] = "-" to tempvariable[i] == '-' in CreateVector().
= is the assignment operator, == is the comparison operator. Also, single characters are surrounded by single quotes, not double quotes.

void reverseVector(vector<int>& userinput)
{
int amountofspots = userinput.size();
vector<int> tempvector;
for (int i = 0; i < amountofspots; i++)
tempvector.push_back(userinput.at(amountofspots - i));
should probably be
void reverseVector(vector<int>& userinput)
{
int amountofspots = userinput.size();
vector<int> tempvector;
for (int i = 1; i < amountofspots+1; i++) // Index error
tempvector.push_back(userinput.at(amountofspots - i));

The following:
for(int i = 1; i <= tempvariable.size(); i++)
{
if (tempvariable[i] = "-" || isdigit(tempvariable[i]))
Must become:
for(int i = 0; i < tempvariable.size(); i++)
{
if (tempvariable[i] == '-' || isdigit(tempvariable[i]))
Explanation:
String indices start from 0 and end at size() - 1.
[i] returns a single char. "-" is not a single char but an entire string literal. You cannot directly compare a single char with an entire string. -, however, is a single char, so that comparison will work.
= is not comparison but assignment. == is used for comparison. As your compiler should have warned you!
Note that there are further problems with your code:
if (i = (amountofspots - 1))
You are again mixing assignment and comparison. Make that ==. And pay attention to compiler warnings!
And finally, isdigit is not exactly a great function. In order to really use it correctly, you'd first have to cast the operand to int and at the same time make sure it is not an invalid value, as documented here.
Why don't you just catch the exception thrown by stoi if the specified string cannot be parsed?

Related

2d array comparing with char

I have an array that reads data from a file, the data is binary digits such as 010011001001 and many others so the data are strings which I read in to my 2d array but I am stuck on comparing each value of the array to 0. Any help would be appreciated.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string myArr[5000][12];
int i = 0, zeroCount = 0, oneCount = 0;
ifstream inFile;
inFile.open("Day3.txt");
while(!inFile.eof())
{
for(int i = 0; i < 5000; i++)
{
for(int j = 0; j < 12; j++)
{
inFile >> myArr[i][j];
j++;
}
i++;
}
}
for(int j = 0; j < 12; j++)
{
for(int i = 0; i < 5000; i++)
{
if(myArr[i][j].compare("0") == 0)
{
zeroCount++;
}
else
{
oneCount++;
}
i++;
}
if(zeroCount > oneCount)
{
cout << "Gamma is zero for column " << i << endl;
}
else
{
cout << "Gamma is One for column " << i << endl;
}
j++;
}
}
some input from the text file:
010110011101
101100111000
100100000011
111000010001
001100010011
010000111100
Thank you for editing you question and providing more information. Now, we can help you. You have 2 major misunderstandings.
How does a for loop work?
What is a std::string in C++
Let us start with the for loop. You find an explanation in the CPP reference here. Or, you could look also at the tutorial shown here.
The for loop has basically 3 parts: for (part1; part2; part3). All are optional, you can use them, but no need to use them.
part1 is the init-statement. Here you can declare/define/initialize a variable. In your case it is int i = 0. You define a variable of data type int and initialize it with a value of 0
part2 is the condition. The loop will run, until the condition becomes false. The condition will be check at the beginning of the loop.
part3 is the so called iteration-expression. The term is a little bit misguiding. It is basically a statement that is executed at the end of the loop, before the next loop run will be executed and before the condition is checked again.
In Pseudo code it is something like this:
{
init-statement
while ( condition ) {
statement
iteration-expression ;
}
}
which means for the part of your code for(int j = 0; j < 12; j++)
{
int j = 0; // init-statement
while ( j < 12 ) { // while ( condition ) {
inFile >> myArr[i][j]; // Your loop statements
j++; // Your loop statements PROBLEM
j++; // iteration-expression from the for loop
}
}
And now you see the problem. You unfortunately increment 'j' twice. You do not need to do that. The last part3 of the for loop does this for you already.
So please delete the duplicated increment statements.
Next, the std::string
A string is, as its names says, a string of characters, or in the context of programming languages, an array of characters.
In C we used to write actually char[42] = "abc";. So using really a array of characters. The problem was always the fixed length of such a string. Here for example 42. In such an array you could store only 41 characters. If the string would be longer, then it could not work.
The inventors of C++ solved this problem. They created a dynamic character array, an array that can grow, if needed. They called this thing std::string. It does not have a predefined length. It will grow as needed.
Therefore, writing string myArr[5000][12]; shows that you did not fully understand this concept. You do not need [12], becuase the string can hold the 12 characters already. So, you can delete it. They characters will implicitely be there. And if you write inFile >> myString then the extractor operator >> will read characters from the stream until the next space and then store it in your myString variable, regardless how long the string is.
Please read this tutorial about strings.
That is a big advantage over the C-Style strings.
Then your code could look like:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string myArr[5000];
int zeroCount = 0, oneCount = 0;
ifstream inFile;
inFile.open("Day3.txt");
while (!inFile.eof())
{
for (int i = 0; i < 5000; i++)
{
inFile >> myArr[i];
}
}
for (int i = 0; i < 5000; i++)
{
zeroCount = 0; oneCount = 0;
for (int j = 0; j < 12; j++)
{
if (myArr[i][j]== '0')
{
zeroCount++;
}
else
{
oneCount++;
}
}
if (zeroCount > oneCount)
{
cout << "Gamma is zero for column " << i << endl;
}
else
{
cout << "Gamma is One for column " << i << endl;
}
}
}
But there is more. You use the magic number 5000 for your array of strings. This you do, because you think that 5000 is always big enough to hold all strings. But what, if not? If you have more than 5000 strings in your source file, then your code will crash.
Similar to the string problem for character arrays, we have also a array for any kind of data in C++, that can dynamically grow as needed. It is called std::vector and you can read about it here. A tutorial can be found here.
With that you can get rid of any C-Style array at all. But please continue to study the language C++ further and you will understand more and more.
Ther are more subtle problems in your code like while(!inFile.eof()), but this should be solved later.
I hope I could help

C++ delete duplicates from cstring [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a c-string that looks something like ABBBCACACACBA and I'm supposed to create a function that deletes the duplicate characters so I end up with ABC. I created a nested for loop that replaces every letter that matches the letter in the outer loop with a \0 and increments a counter that keeps track of the repeats. I'm getting -1 as the amount of repeats that should be documented, and from checking it spits out ABBC instead of ABC. I'm stumped, any ideas?
for (int i = 0; i < SIZE; i++)
{
for (int j = i + 1; j < SIZE; j++)
{
if (letter[i] == letter[j])
{
letter[j] = '\0';
repeatCounter++;
}
}
}
It is not enough to just replace duplicates with '\0', you have to actually remove them from the string and shift the remaining characters down. Try something more like this:
int size = SIZE, i = 0;
while (i < size)
{
int j = i + 1;
while (j < size)
{
if (letter[j] == letter[i])
{
for (int k = j + 1; k < size; k++)
{
letter[k-1] = letter[k];
}
letter[--size] = '\0';
repeatCounter++;
continue;
}
j++;
}
i++;
}
Live Demo
Here's a simple example which does what you want. It uses std::string to store the output. You can copy-n-paste the code here to test and run. Look into using std::string as it has functions which will make your life easy.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input("ABBBCACACACBA");
string output;
for(size_t i = 0; i < input.size(); i++)
{
if(output.find(input[i]) == string::npos)
{
output += input[i];
}
}
cout << "Input: " << input << endl;
cout << "Output: " << output << endl;
return 0;
}

duplicate name checking function for an array

I am still a beginner in C++, so I'm sorry if the question is simple.
I am trying to build a program that asks you to input names and register them to an array. Then, I need to call a function to check if there are any duplicate names. If there are any, it asks the user to input another name.
The problem I'm having is that the function is called whether or not there are duplicates, and always replaces the first name that was entered.
int checking(string stringArray[5]) {
int i, z ;
for (i = 0; i < 5; i++) {
for (z = 0; z < 5; z++) {
if (z != i) { // Makes sure don't check number against itself
if (stringArray[z] == stringArray[i]) {
return i;
}
else {
return 0;
int main(){
for (i = 0; i < 5; i++) {
cin >> stringArray[i];
}
j = checking(stringArray);
if (j == 0) {
cout << "Please re-enter name " << ". Duplicate names are not allowed"
<<'\n';
cin >> stringArray[j];
}
Some observations (ignoring the syntax errors, I assume these are not present in your actual code):
z doesn't need to start at 0 every time, it can start at i + 1 because you dont need to check pairs you have already checked (makes it simpler and runs faster)
you don't want to return in your loop, it will prevent you from checking past the first repeated name. Instead move your reenter statement into the loop.
generally you dont want to use literals (5) in a loop, instead use a variable to store the length of the array and compare to that (this is just a general programming rule, it won't change how the code runs)
Your final checking() function should look closer to:
void checking(string stringArray[5]) {
int i, z ;
// consider replacing 5 with a variable
for (i = 0; i < 5; i++) {
for (z = i+1; z < 5; z++) {
if (stringArray[z] == stringArray[i]) {
cout << "Please re-enter name " <<
". Duplicate names are not allowed" <<'\n';
cin >> stringArray[z];
/* restart the loop user may have entered a */
/* second duplicate from previous entries */
i = 0;
z=i+1;
}
}
}
}

Filling up the vector with given input and searching a word on it later

Here, i am editing my question.
while (iter <= k && getline(input, line))
{
searchWord.clear();
int len = line.length();
if (len == 0) // getline function was not getting the third line. It was empty so. at 2-3 lines below. It was giving run time error because it was trying to access a vector's element fileed with empty string(line)
{
cout << count << " Words are Found:" << total_words << endl;
return 0;
}
for (int i = 0; i < len; i++)
{
ch1 = line.at(i);
searchWord.push_back(ch1);
}
for (int col = 1; col <= n; col++)
{
for (int row = 1; row <= n; row++)
{
if (mat[col][row] == searchWord[0]) // aranıalcak kelımenın boyutuna erisılene kadar harf harf matrix in ilk harfi ile aranan kelımenın ılk harfı sonra 2. harfı uyuyot mu dıye bakılacak bu loop un ıcıne spiral gitme algoritması yazılacak.
{
if (found(mat, searchWord, row, col)) // spiral arama loop u
{
count++;
for (int i = 0; i < searchWord.size(); i++) // if word is found add it to total words and afterwards leave a space.
{
total_words += searchWord[i];
}
total_words += " ";
}
}
}
}
row = 1;
iter++;
}
this code does not work for 3rd time .For example lets say this is our file contains these words seperated with only enter
EXAM
QUIZ
NOTFOUND
it gets exam and quiz perfectly and does eerything right. But it does not gets "NOTFOUND" in line at 3rd iteration of loop. So it does not enter the for loop at beginning and it crashes when it tries to reach outside of the searchWord vector.
What could be done ?
Firstly, I think this might be helpful to your problem
Secondly, in this line
mat[row][col] == ch;
you are comparing an element of matrix with ch
What you really just need to do:
mat[row][col] = ch;
It's a common mistake, so don't forget that comparison operator == is used only when you need to get a bool, and assignment operator = is, well, assignment to some variable.

Sorting out duplicates between 2 char arrays [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm struggling with an assignment for my class where we have to take input from the user into a char array (word) and take out the duplicates in the word inputted if needed. Comparing the array of the modified array (word) with the alphabet array (abc) to remove the repeated letters from the list. Once the duplicates are removed then just output the modified word followed by the new form of the alphabet into the newAbc array.
For example:
The word HELLO would first become HELO then after comparing to the alphabet the end output from the new array should be HELOABCDFGIJKMNPQRSTUVXYZ.
I'm stuck more on the for loops comparing the new word to the alphabet really.
char word[20], newAbc[40] = { '\0' };
char abc[27] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int i = 0, b = 1, n = 0, leng, dup;
//dup counts up the repeats but is established in the first portion of the program but i've excluded it as it works perfectly.
cout << "Please enter a word: ";
cin >> word;
leng = strlen(word);
b = 0;
n = leng - dup;
i = 0;
for (i = 0; i < n; i++)
{
for (b = 0; b < 27; b++)
{
if (newAbc[i] != abc[b])
{
newAbc[n] = abc[b];
n++;
}
}
}
for (i = 0; i < 27; i++)
cout << newAbc[i];
cout << endl;
return 0;
}
I'd appreciate any kind of insight on my mistakes.
The major problem for crash is that you are changing n inside for loop for iterating in newAbc. And your if condition will be true for at least 25 times so incrementing n by 25(minimum) in each iteration resulting in accessing out of bound memory(SEG-FAULT).
for (i = 0; i < n; i++)
{
for (b = 0; b < 27; b++)
{
if (newAbc[i] != abc[b]) // this condition is not correct
{ // this will be true atleast 25 times
newAbc[n] = abc[b]; // wrong memory access
n++; // here is the problem
}
}
}
Assuming that your duplicate counting works fine, below are the changes required:-
char word[20];
// FIXME: your new array should not contain no duplicate so size can be 27
char newAbc[40] = {'\0'};
// FIXME: simply can be char abc[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char abc[27] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
cout << "Please enter a word: ";
cin >> word;
// dup counts up the repeats but is established in the first portion of
// the program but i've excluded it as it works perfectly.
// Lets say word = "HELLO"; so dup = 1, and newArray, should have "HELO"
memcpy(newAbc, "HELO", 4); // from your excluded part of code
int dup = 1; // from your excluded part of code
int leng = strlen(word); // length of input word
int n = leng - dup; // char remained to be inserted
// iterator for new array(newAbc)
int c = n; // n elements are already there
// Just reversed your loop
for (int b = 0; b < 27; b++)
{
int found = 0;
for (int i = 0; i < n; i++)
{
if (newAbc[i] == abc[b])
{
found = 1;
break;
}
}
if (!found)
{
newAbc[c] = abc[b];
c++;
}
}
for (int i = 0; i < 27; i++)
cout << newAbc[i];
cout << endl;
return 0;