So I'm trying to have the user enter strings that will be put into an array with the maximum size of 50 strings. Whenever the user enters "stop", I want the loop to stop and the array to cutoff there.
I then want to read the array back to the user. I tried running this and got a really weird error. Can someone explain to me why this doesn't work and how I would fix it? Thanks.
int main(int argc, const char * argv[]){
string array[50];
// Get's inputs for array
for(int i = 0; i < 50; i++){
cout << "Enter string: ";
getline(cin, array[i]);
if(array[i]== "stop"){
array[i] = "\0";
break;
}
}
// Reads inputs from array
for(int i = 0; i < sizeof(array); i++){
cout << array[i] << "\n";
}
return 0;
}
I don't know why I'm getting down voted so hard?
Use std::vector for your task. It has the method push_back() where you can add elements dynamically. Also you can check the size of the vector easily by calling vector.size().
int main(int argc, const char * argv[]){
vector<std::string> array;
// Get's inputs for array
for(int i = 0; i < 50; i++){
cout << "Enter string: ";
string line;
std::getline(cin, line);
array.push_back(line);
if(array[i]== "stop"){
array[i] = "\0";
break;
}
}
// Reads inputs from array
for(int i = 0; i < array.size(); i++){
cout << array[i] << "\n";
}
return 0;
}
In your code you would have to implement a counter that counts, how many inputs the user did.
Normally you would use vectors, but since you have not reached that section of the book, I guess they want you to solve it with C-style arrays.
You can get the length of a C-style array like this
int size = (sizeof(array)/sizeof(*array)
But since you know the maximum number of entries are 50 and that you must stop when you reach the word stop, maybe you rather want this
for(int i = 0; i < 50; i++){
if (array[i] == '\0')
break;
cout << array[i] << "\n";
}
I just implemented a loop to find out how long the array is.
// Determines how long the array is
for(int i = 0; i < 50; i++){
if(array[i] == "\0"){
break;
}
counter++;
}
Related
c++
When printing to console, if function execution is sequential it would seem logical the ordered array would be printed after calling insertionSort, however order list does not print until next loop. Any help would be appreciated.
#include <stdio.h>
#include <iostream>
#include <array>
using namespace std;
void insertionSort(int* array, int size) {
for (int i = 1; i < size; i++) {
int key = i - 1;
while (i > 0 && array[key] > array[i] ) {
int tmp = array[i];
array[i] = array[key];
array[key] = tmp;
i -= 1;
key -= 1;
}
}
}
const int ARRAY_MAXSIZE = 5;
int main(void) {
int *array = (int*)calloc(ARRAY_MAXSIZE, sizeof(int));
int input;
cout << "Enter 5 digits\n";
for (int size=0; size < ARRAY_MAXSIZE; size++) {
cout << size << " index ";
cin >> input;
array[size] = input;
insertionSort(array, size);
for (int j=0; j <= size; j++) {
cout << array[j];
}
cout << '\n';
}
}
Console Entry
This is a classic off-by-one error. Your insertionSort expects you to pass the number of elements to sort via the parameter size. But your main loop is always holding a value that is one less than the size immediately after adding an element.
I want to say that bugs like this are easily discovered by stepping through your program's execution with a debugger. If you don't know how to use a debugger, start learning now. It is one of the most important tools used by developers.
Anyway, the quick fix is to change your function call to:
insertionSort(array, size + 1);
However, as Paul McKenzie pointed out in comments, it's a bit crazy to do this every time you add a new element because your function sorts an entire unsorted array. Your array is always nearly sorted except for the last element. You only need to call that function once after your input loop is done:
// Read unsorted data
for (int size = 0; size < ARRAY_MAXSIZE; size++) {
cout << size << " index ";
cin >> input;
array[size] = input;
}
// Sort everything
insertionSort(array, ARRAY_MAXSIZE);
// Output
for (int j = 0; j < ARRAY_MAXSIZE; j++) {
cout << array[j];
}
cout << '\n';
But if you want every insertion to result in a sorted array, you can "slide" each new value into place after inserting it. It's similar to a single iteration of your insertion-sort:
// Sort the last element into the correct position
for (int i = size; i >= 1 && array[i] > array[i - 1]; i--)
{
std::swap(array[i], array[i - 1]);
}
Even better, you don't need to swap all those values. You simply read the value, then shuffle the array contents over to make room, then stick it in the right spot:
// Read next value
cin >> input;
// Shuffle elements to make room for new value
int newPos = size;
while (newPos > 0 && array[newPos - 1] > input) {
array[newPos] - array[newPos - 1];
newPos--;
}
// Add the new value
array[newPos] = input;
I have the following code that does exactly what I want. The problem is that I need the sample array to compare the strings and keep the count. Is there a way to count the number of occurrences of each string on any array without a sample?
For a little bit more context, the initial problem was to read data from a .txt file including vehicles information, like:
Volkswagen Jetta
Ford Focus
Volkswagen Jetta
And count the number of vehicles of each brand. Keep in mind that this is from an introductory course for programming, and we don't know how to use vectors or maps.
#include <iostream>
#include <string>
using namespace std;
using std::string;
#define MAX 20
int main(){
int counter[MAX];
string arr[MAX]={"ABC","AOE","ADC","ABC","ADC","ADC"};
string sample[MAX]={"ABC", "AOE", "ADC"};
for(int i=0; i<=MAX; i++){
counter[i]=0;
}
for(int i=0; i<MAX;i++){
for(int j=0; j<MAX; j++){
if (sample[i]==arr[j]){
counter[i]++;
}
}
}
for(int i=0; i<3;i++){
cout<< sample[i] << "=" << counter[i]<<endl;
}
return 0;
}
All you are expected to do is keep a list (an array will do) of brand names, and an array of counts for each name:
std::string brand_names[100];
int counts[100]; // number of times each element of brand_names[] was read from file
int num_items = 0;
Each time you read a brand name from file, try to find it in the array of strings. If found, just add one to the count at the same index. If not found, add it to the end of the brand_names[] array, add 1 to the end of the counts[] array, and increment num_items.
You do not need anything more than a simple loop for this:
an outer loop to read the next brand name from file
an inner loop to try to find the brand name in the list
If you want to solve this problem without knowing the initial values of the sample array:
Create an empty sample array. When you see new elements add them to this array.
Use a variable sample_size to keep track how many samples have been seen. Below is a simple example which doesn't use std::vector or dynamic allocation.
int main()
{
std::string arr[MAX] = { "ABC","AOE","ADC","ABC","ADC","ADC" };
std::string sample[MAX];
int sample_size = 0;
int counter[MAX] = { 0 };
for (int i = 0; i < MAX; i++)
{
if (arr[i].empty()) break;
bool sample_found = false;
for (int j = 0; j < sample_size; j++)
if (arr[i] == sample[j])
{
sample_found = true;
counter[j]++;
break;
}
if (!sample_found)
{
sample[sample_size] = arr[i];
counter[sample_size]++;
sample_size++;
}
}
for (int i = 0; i < sample_size; i++)
cout << sample[i] << "=" << counter[i] << std::endl;
return 0;
}
as the title says I'm attempting to compare elements in an array. My intent is to have the user enter 3 integers into the program, thereafter it should increment through this array comparing the the 1st number to the 2nd, and so forth and swapping the element's from order of lowest to highest.
My issue currently is that it will swap the first and second elements but the third causes an integer overflow due to me comparing and assigning an integer in an index higher than the initialized array can hold.
I'm currently drawing a blank as to how I could still compare these numbers in this manner without causing it to overflow.
A hint or perhaps a whole different perspective would be appreciated.
#include "E:/My Documents/Visual Studio 2017/std_lib_facilities.h"
int main()
{
cout << "Enter three integers: \n";
int numbersArray[3];
int temp = 0; //This lets us hold our integers temporarily so we can swap them around in the array
//This enters integers as elements in the array
for (int i = 0; i < 3; i++)
{
cin >> numbersArray[i];
}
//This should swap the elements from smallest to greatest
for (int i = 0; i = 3; i++)
{
if (numbersArray[i] > numbersArray[i+1])
temp = numbersArray[i];
numbersArray[i] = numbersArray[i+1];
numbersArray[i+1] = temp;
//swap(numbersArray[i], numbersArray[++i]);
}
//This prints the index's containing the elements in the array
for (int i = 0; i < 3; i++)
{
cout << numbersArray[i] << ' ';
}
cout << endl;
keep_window_open();
return 0;
}
You will need to modify this to suit your needs, but this should get you on the right track. One important thing to investigate is how you decided to sort the elements. Your sorting needs to be looped, otherwise, you won't necessarily sort the entire array (depending on your inputs).
#include <iostream>
using namespace std;
int main()
{
cout << "Enter three integers: \n";
int numbersArray[3];
int temp = 0; //This lets us hold our integers temporarily so we can swap them around in the array
//This enters integers as elements in the array
for (int i = 0; i < 3; i++)
{
cin >> numbersArray[i];
}
for(int loop = 0; loop <3; loop++){
//This should swap the elements from smallest to greatest
for (int i = 0; i < 2; i++)
{
if (numbersArray[i] > numbersArray[i+1]){
temp = numbersArray[i];
numbersArray[i] = numbersArray[i+1];
numbersArray[i+1] = temp;
}
//swap(numbersArray[i], numbersArray[++i]);
}
}
//This prints the index's containing the elements in the array
for (int i = 0; i < 3; i++)
{
cout << numbersArray[i] << ' ';
}
cout << endl;
return 0;
}
I want to make a program that lets the user insert some numbers to the array and the print it out afterwards. Problem is when I try to do that (lets say the size of my array is 100) then:
What it should do: Inserted- 1,2,3,4,5 -> should print 1,2,3,4,5
But instead it prints -> 1,2,3,4,5,0,0,0,0,0,0, .... up to the size of my array.
Is there any way I can get rid of those zeros?
Code:
int SIZE = 100;
int main()
{
int *numbers;
numbers = new int[SIZE];
int numOfElements = 0;
int i = 0;
cout << "Insert some numbers (! to end): ";
while((numbers[i] != '!') && (i < SIZE)){
cin >> numbers[i];
numOfElements++;
i++;
}
for(int i = 0; i < numOfElements; i++){
cout << numbers[i] << " ";
}
delete [] numbers;
return 0;
}
You increase numOfElements no matter what the user types. Simply do this instead:
if(isdigit(numbers[i]))
{
numOfElements++;
}
This will count digits, not characters. It may of course still be too crude if you want the user to input numbers with multiple digits.
Get numOfElements entered from user beforehand. For example
int main() {
int n;
cin >> n;
int * a = new int[n];
for (int i = 0; i < n; ++i)
cin >> a[i];
for (int i = 0; i < n; ++i)
cout << a[i] << endl;
delete[] a;
}
Input
4
10 20 30 40
Output
10 20 30 40
Since you declared array size, all indices will be zeros.
User input changes only the first x indices from zero to the value entered (left to right).
All other indices remains 0.
If you want to output only integers different from 0 (user input) you can do something like that:
for(auto x : numbers){
if(x!=0)cout<<x<<" ";
}
You can use vector and push_back the values from user input to get exactly the
size you need without zeros, then you can use this simple code:
for(auto x : vectorName)cout<<x<<" ";
Previous solutions using a counter is fine.
otherwise you can (in a while... or similar)
read values in a "temp" var
add if temp non zero
exit loop if counter >= SIZE-1 (you reach max slots)
increment counter
when You will print, form 0 to counter, you will get only non zero values.
I am attempting to fill an array backwards from 20 to 0 but whenever I print it out it still prints out forwards. For instance I want to put in 1,2,3,4,5 and have it come out as 5,4,3,2,1.
I have attempted to do a for loop that counts backwards from 20 to 0 but when i print it it is still coming out incorrect. Any help?
int temp;
for (int i = 20; i > 0; i--)
{
cout << "Please enter the next number. Use a -1 to indicate you are done: ";
cin >> temp;
while(temp > 9 || temp < -2)
{
cout << "You may only put numbers in 0 - 9 or -1 to exit. Please enter another number: ";
cin >> temp;
}
arr1[i] = temp;
cout << arr1[i];
}
for (int i = 21; i > 0; i--)
{
cout << arr1[i];
What's the size of your array?
Assume that the size is 21 (indexes from 0 to 20).
First of all please note that your first loop will never populate the array at index 0 (something like this arr1[0] = temp will never be executed inside your first loop).
If you want to avoid this behavior you should write your first for loop like this:
for (int i = 20; i >= 0; i--){...}.
The second for loop has some issues:
You are traversing the array backwards while you want to do the opposite.
The loop starts from an index out of bound (21).
The loop may print some undefined values (You should remember the index of the last added value).
I suggest you to use other data structures like a Stack but if you want to use an array you can edit your code as follows:
int i;
for (i = 20; i >= 0; i--){...}
for (i; i <= 20; ++i) { cout << arr1[i]; }
If you don't want to declare int i; outside of the loop you can do something like that:
int lastAdded;
for (int i = 20; i >= 0; i--){
...
lastAdded = i;
}
for (int i = lastAdded; i <= 20; i++) { cout << arr1[i]; }
Edit: Note that neither your code nor mine stops asking for a new value after the insertion of a -1.
If you want to achieve this behavior you should use a while loop instead of the first for loop and check for the exit condition.