I tried the code below to return an array with all string ids, but it didn't work.
The output just returns a number. How can I return an array with ids?
#include <iostream>
#include <string>
using namespace std;
string* getArray()
{
int nanim;
cout << "Enter the number of animals: ";
cin >> nanim;
string *id = new string[nanim];
for ( size_t i=0; i < nanim; i++ )
{
cout<< "\nEnter id anim "<< i+1 << ": ";
cin >> id[i];
}
for ( size_t i = 0; i < nanim; i++ )
{
cout << id[i] << endl;
}
return id;
}
int main()
{
int n;
cin>>n;
string* anim[n]=getArray();
cout<<anim;
return 0;
}
You are returning a pointer to the first element in the array.
To access array elements just having called string* arr = getArray(); you can use arr[0], arr[1], arr[2] etc. to access the strings.
Don't forget to delete the memory you allocated in the function though; at the moment you have a big memory leak.
Generally this is not good programming though since the function caller doesn't know how many elements there are in the returned array. It would be better to get the number of animals in the caller and pass that into your function.
Better still, rebuild your code to use std::vector as I see you're already using stl. Then you don't need to worry (explicitly) about memory allocation and deallocation.
You do not need to read the number of elements twice, and the type of the anim should be string*, not string* []. Unfortunately, this wouldn't tell you the number of items in the array, so you need to get it from the getArray, for example, like this:
string* getArray(int& nanim) {
// Remove the declaration of nanim, and keep the rest of the code unchanged
...
}
int main()
{
int n;
string* anim = getArray(n);
for (int i=0; i != n; i++) {
cout << anim[i] << endl;
}
delete[] anim;
return 0;
}
This is not an optimal C++ solution, though: you would be much better off using std::vector instead of an array, because the vector grows dynamically, and its size is returned along with the container itself. There would be no need to delete[] the result either, which would significantly simplify your code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> getVector()
{
int nanim;
cout << "Enter the number of animals: ";
cin >> nanim;
vector<string> res;
for ( size_t i=0; i < nanim; i++ )
{
cout<< "\nEnter id anim "<< i+1 << ": ";
string tmp;
cin >> tmp;
res.push_back(tmp);
}
return res;
}
int main()
{
vector<string> anim = getVector();
for ( size_t i = 0; i < anim.size(); i++ )
{
cout << anim[i] << endl;
}
return 0;
}
Related
#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>
using namespace std;
void getinput (string &first,string &second);
void lengthcheck (string first, string second);
//int anagramcheck (string word);
int* lettercounter (string input);
int main()
{
std::string a;
std::string b;
getinput(a,b);
lengthcheck (a,b);
lettercounter(a);
lettercounter(b);
int* one = lettercounter(a);
int* two = lettercounter(b);
if (one == two)
cout << "You Have Entered An Anagram" << endl;
else
cout << "You Have Not Entered An Anagram" << endl;
}
void getinput (string &first, string &second) {
cout << "Enter First Input: ";
getline(cin, first, '\n');
cout << "Enter Second Input: ";
getline(cin, second, '\n');
cout << "You Entered " << first << " and " << second <<endl;
}
void lengthcheck(string first, string second){
int lengtha = first.length();
int lengthb = second.length();
if ((lengthb > 60) || (lengtha > 60)) {
cout << "Input Is Invalid" << endl;
} else if (lengtha !=lengthb) {
cout << "Input is not an anagram" << endl;
} else {
cout << "Input is Valid" << endl;
}
}
int* lettercounter(string input)
{
static int freq[26] = {0};
int length = input.length();
for (int i=0; i<26; i++) {
freq[i]=0;
}
for (int i=0; i <length; i++) {
if(input[i]>='a' && input[i]<='z')
{
freq[input[i] - 97]++;
}
else if(input[i]>='A' && input[i]<='Z')
{
freq[input[i] - 65]++;
}
}
for(int i=0; i<26; i++) {
/* If current character exists in given string */
if(freq[i] != 0)
{
printf("'%c' = %d\n", (i + 97), freq[i]);
}
return freq;
}
}
I am having trouble returning the array named freq from the user definied function called lettercount. Can someone give me a hint? I need the lettercount to return an array. I need to call the function lettercount twice so i can compare the results of each array to determine if the two inputs are anagrams. I am not sure if the function is returning an actual value to the main.
First of all, freq shouldn't be static. By making it static, you would be accessing the same array everytime. For what you want to do, you don't want to always access the same memory.
In second place, you cannot just return a pointer to memory that has not being allocated dynamically or that isn't static. When you get out of scope (i.e. you return from the function lettercounter back to main), the memory that was occupied by the array will be freed. So, you would be returning a pointer to memory that is no longer reserved, resulting in undefined behavior.
If you really need to work with raw pointers, then each time you enter lettercounter, you would need to allocate memory for the array dynamically like this: int * freq = new int[26];. This will reserve memory for an array of size 26. Then, when you return freq, the memory will still be allocated. However, don't forget that the memory allocated with new doesn't delete itself. You have to clean your mess. In this case, at the end of main you would call delete[] one; and delete[] two;.
int* lettercounter(string input)
{
int * freq = new int[26];
.
.
.
return freq;
}
int main()
{
.
.
int* one = lettercounter(a);
int* two = lettercounter(b);
.
.
delete[] one;
delete[] two;
}
In any case, I'd recommend you to learn to use smart pointers and about standard containers (like a vector). These operations would be much simpler.
I'm learning c++ and I'm trying to ask the user to input 4 numbers in a function, and then simply print the array.
int getFourNums();
int main(int argc, char** argv){
int getNums;
getNums = getFourNums();
cout << "The array is: " getNums << endl;
}
int getFourNums(){
int i;
int myArray[4];
cout << "Enter 4 nums: ";
for(i = 0; i < 4; i++){
cin >> myArray[i];
}
return myArray[i];
As of now, it's letting me get the four numbers, but the result that's printing is "The array is: 0." I'm not quite sure why the array is seemingly not populating.
Your fundamental problem is that int getFourNums() can only return a single integer, not an array of them. The next problem is that functions cannot return raw arrays for historical reasons. Your choices are to return a std::array, a struct containing the array, pass the array by reference into the function, or return a std::vector. My preference for this application is a std::vector - it is flexible, and although not quite as efficient as std::array, you should probably default to std::vector unless you have a good reason otherwise. Your getNums code would then look like:
std::vector<int> getFourNums() {
std::vector<int> result;
cout << "Enter 4 nums: ";
for(int i = 0; i < 4; i++){
int v;
cin >> v;
result.push_back(v);
}
return result;
}
To print the vector, see this question. My personal preference would be a range-based for loop over the vector; your tastes may vary.
One issue in your code is that a loop like
for(i = 0; i < 4; i++){
cin >> myArray[i];
}
will end up with i==4. Hence, return myArray[i] will exceed array bounds and/or access an uninitialised value then and yield undefined behaviour.
The main issue, however, is that in C++ you'll follow a very different approach and use collection types like std::vector instead of plain arrays. See the following code illustrating this. Hope it helps.
#include <vector>
#include <iostream>
std::vector<int> getFourNums(){
int val;
std::vector<int> result;
cout << "Enter 4 nums: ";
for(int i = 0; i < 4; i++){
cin >> val;
result.push_back(val);
}
return result;
}
int main(int argc, char** argv){
std::vector<int> fourNums = getFourNums();
for (auto i : fourNums) {
cout << i << endl;
}
}
int getFourNums() will only let you return one int, not the whole array and return myArray[i]; is out of bounds since i == 4. You can only use the range [0,3] as indices for your array. Here's a reworked version with comments in the code.
#include <iostream>
#include <vector>
// don't do "using namespace std;" since it includes
// a lot of stuff you don't need.
// Here's a function that will return a vector of int's
// It'll behave much like a C style array
// but can have variable length and you can use
// a lot of standard functions on it.
std::vector<int> getNums(size_t count) {
// The "array" we'll return with "count" number of
// default constructed int:s (they will all be 0):
std::vector<int> myArray(count);
std::cout << "Enter " << count << " nums: ";
// A range based for loop that will go through
// all int:s in "myArray". "num" will be
// a reference to each int in the vector which
// means that if you change the value of "num",
// you'll actually change the value in the vector.
for(int& num : myArray) {
// read values into the int currently
// referenced by num
std::cin >> num;
}
// return the vector by value
return myArray;
}
// Put main() last so you don't have to forward declare the functions
// it uses
int main() {
// call getNums with the value 4 to read 4 int:s
std::vector<int> Nums = getNums(4);
std::cout << "The array is:";
// print each int in the vector. There's no need to use
// a reference to the int:s here since we won't be changing
// the value in the vector and copying an int is cheap.
for(int num : Nums) {
std::cout << " " << num;
}
// std::endl is rarely good when you only want to output a newline.
// It'll flush the buffer with is costly.
// Make a habit of using "\n" in most cases.
std::cout << "\n";
}
I see that you want to return entire array but just look at your return type:
int getFourNums()
You're returning an integer right? In this situation the returned integer is always myArray[4]. Be aware that it's an integer value, you're returning something that doesn't belong to you actually!
So what to do? I suggest you to pass your array to function like this:
void getFourNums(int myArray[]){
int i;
cout << "Enter 4 nums: ";
for(i = 0; i < SIZE; i++){
cin >> myArray[i];
}
}
Now you filled your array. How to print your array then? We can't simply give our array name and tell cout to print it like you did (you couldn't actually!). Nothing magical here. We're going to print your array's element one by one:
void printFourNumbers(int array[])
{
for(int i = 0 ; i < SIZE ; ++i)
{
cout << array[i] << endl;
}
}
Finally whole code looks like this:
#include <iostream>
using namespace std;
const int SIZE = 4;
void getFourNums(int myArray[]);
void printFourNumbers(int array[]);
int main(int argc, char** argv){
int myArray[SIZE];
getFourNums(myArray);
printFourNumbers(myArray);
}
void getFourNums(int myArray[]){
int i;
cout << "Enter 4 nums: ";
for(i = 0; i < SIZE; i++){
cin >> myArray[i];
}
}
void printFourNumbers(int array[])
{
for(int i = 0 ; i < SIZE ; ++i)
{
cout << array[i] << endl;
}
}
I created a simple program to help me understand how to Dynamically Allocate a structure. I want the program to gets 5 names and 5 accounts from the user, and display the names and the accounts. I know a pointer is like a reference variable, the only differences instead of passing the value, it passes the address of the variable. I set a breaking point for line 23 ("getline(std::cin,clientPtr[count].name);"), line 25 ("std::cin.ignore(std::numeric_limits::max(),'\n');"),
line 27 ("std::cin >>clientPtr[count].accounts;"), line 40 ("std::cout <<"Name:" << clientPtr[count].name;"), line 41 ("std::cout <<"Name:" << clientPtr[count].name;"),line 31( showInfo(&client);). When I debugged it shows that line 41 is not executing. It should display the names and the accounts of each client. In this case it's not. I'm not sure why, just a little background on me, I'm new to C++, as well with using the debugger. I'm using xcode 8.2 and the debugger I am using is lldb. I'm here to learn, so anything will help. Thanks.
#include <iostream>
#include <limits>
struct BankInfo
{
std::string name;
std::string accounts;
};
void showInfo(BankInfo*);
int main()
{
BankInfo client;
BankInfo* clientPtr=nullptr;
clientPtr = new BankInfo[5];
for(int count =0; count < 5; count++)
{
std::cout << "Enter your name:";
getline(std::cin,clientPtr[count].name);
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Enter you account number:";
std::cin >>clientPtr[count].accounts;
}
showInfo(&client);
return 0;
}
void showInfo(BankInfo* clientPtr)
{
for(int count =5; count < 5; count++)
{
std::cout <<"Name:" << clientPtr[count].name;
std::cout <<"Account:" << clientPtr[count].accounts;
}
}
You are handing the wrong thing to showInfo(). You have two variables.. a single BankInfo variable and a dynamic allocated array with size 5.
You want to iterate over the latter and not the former.
Changing showInfo(&client);to showInfo(clientPtr); should do the trick perhaps?
So I fixed the solution I made several mistakes, but thank you for the suggestion. Here's what I did.
#include <iostream>
#include <limits>
struct BankInfo
{
std::string name;
std::string accounts;
};
void showInfo(BankInfo*);
int main()
{
BankInfo client;
BankInfo* clientPtr=nullptr;
clientPtr = new BankInfo[5]; //Allocate an array of BankInfo struct on the heap
for(int count =0; count < 5; count++)
{
std::cout << "Enter your name:";
getline(std::cin,clientPtr[count].name); // stores the value in the name member
std::cout << "Enter you account number:";
std::cin >>clientPtr[count].accounts; // stores the value in accounts member
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
showInfo(clientPtr);
delete [] clientPtr;
clientPtr = nullptr;
return 0;
}
void showInfo(BankInfo* clientPtr)
{
for(int count =0; count < 5; count++)
{
std::cout <<"\nName:" << clientPtr[count].name; // dereference the pointer to the structure
std::cout <<"\nAccount:" << clientPtr[count].accounts; // dereference the pointer to the structure
}
}
for(int count=1 ; count<=5 ; count++)
{
//do your stuff here
}
Here is the code::
#include <iostream>
using namespace std;
const int MAX = 4;
int main ()
{
char key[20];
char *names[MAX];
for (int i=0; i<MAX; i++)
{
cout << " entr keys\n";
cin >> key;
names[i]=key;
cout<< names[i];
}
for(int i=0; i<MAX;i++)
{
cout << names[i];
}
return 0;
}
When I enter the keys and print them in the 1st for loop they show the right value, but when I print names[i] in the 2nd for loop it keeps showing the last key entered again and again.
Please tell me: where am I going wrong?
When you run names[i]=key; you don't really copy key's string value to names[i].
It just makes name[i] point to where key is (since both name[i] & key are pointers).
so all in all you're overwriting key several times, and making all of names pointers point to key.
You need to copy those strings either by working with std::string instead of char* or by using strcpy. I'd recommend on working with std::string.
Using std::string your code should look like this:
#include <iostream>
#include <string>
using namespace std;
const int MAX = 4;
int main ()
{
string names[4];
for (int i = 0; i < MAX; i++)
{
cout << "entr keys" << endl;
cin >> names[i];
cout << names[i];
}
for(int i=0; i<4;i++)
{
cout << names[i];
}
return 0;
}
Every time you execute the lines
cout << " entr keys\n";
cin >> key;
you're inserting a null-terminated string into key, e.g. "hello\0".
Afterwards you copy key's address and store it into a cell of the names pointers array:
names[i]=key; // Now I point to 'key'
cout<< names[i];
then the cycle starts again. Anyway from the second time on you're inserting null-terminated strings into key and thus overwriting the previous contents. The second time if you had entered "hi\0" the contents of the key array would become
['h', 'i', '\0', 'l', 'l', 'o', '\0']
anyway you're going to only print the first string since the null terminator will prevent the other content from being displayed.
When the program ends you're going to have four pointers to the same key array and that array will only contain the last element inserted which overwrote the previous ones.
In order to solve you can make your array a bidimensional one (or use a string array):
const int MAX = 4;
int main ()
{
char key[4][20]; // <- Now this has two indices
char *names[4];
for (int i = 0; i < MAX; i++)
{
cout << " entr keys\n";
cin >> key[i];
names[i]=key[i];
cout<< names[i];
}
for(int i=0; i<4;i++)
{
cout << names[i];
}
return 0;
}
Live Example
Corrected program:
#include <iostream>
using namespace std;
#include <cstring>
const int MAX = 4;
int main ()
{
char key[20];
char *names[MAX];
for (int i = 0; i < MAX; i++)
{
cout << " entr keys\n";
cin >> key;
names[i] = new char[strlen(key) + 1];//names[i]=key;
strcpy(names[i], key);
cout<< names[i];
}
for(int i=0; i<MAX;i++)
{
cout << names[i];
}
for(int i=0; i<MAX;i++)
{
delete [] names[i];
}
return 0;
}
You need to allocate space for each names[i] and when done, deallocate
also, changed the hardcoded 4 to MAX
I'm new to C++ and I need some help creating this program:
I need to ask for the size of the list, then take the list containing integers and then ask the size of the second list and take those integers.
So far I have this:
#include <iostream>
using namespace std;
int main()
{
long int ARR[10];
int i,n;
printf("List 1 size: ");
scanf("%d",&n);
printf("List 1 data: ");
for(i=0;i<n;i++)
{
scanf("%ld",&ARR[i]);
}
So that will take the input for the first list. Now I will repeat this for the second list.
But the key point is I now need to compare the two lists. If list1 is in list2 then I say yay, or if not then nay.
How do I go about comparing these two lists? And I am I on the right track with the input?
Thanks,
EmptyPeace
I think that's what you expected.
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
using namespace std;
bool mypredicate (int i, int j) {
return (i==j);
}
int main(){
int size_list = 0;
vector<int> list1, list2;
cin >> size_list;
list1.resize(size_list);
list2.resize(size_list);
cout << list1.size() << endl;
for (int i = 0; i < size_list; i++)
cin >> list1[i];
for (int i = 0; i < size_list; i++)
cin >> list2[i];
pair<vector<int>::iterator,vector<int>::iterator> mypair;
mypair = mismatch (list1.begin(), list1.end(), list2.begin(), mypredicate);
if( mypair.first == list1.end() && mypair.second == list2.end() )
cout << "are equals" << endl;
else{
cout << "aren't " << endl;
cout << *mypair.first << ", " << *mypair.second << endl;
}
system("pause");
return 0;
}
I think you should use either dynamic array or stl's vector to store data.
for example, dyn. array:
int size;
scanf("%d", size);
int *tab = new int[size];
...
delete[] tab;
or vector way:
#include <vector>
...
int size;
scanf("%d", size);
vector <int> tab(size);
// to insert an element, use tab.push_back( number );
// and getting an element goes array-way, for example tab[0];
And some words from me- if you are writing in c++, use cin and cout for input/output, unless you need extra speed or specific format. And remember, that list is something different than array/vector.