I understand the correct implementation and usage of arrays regarding with indexes and memory locations, but the output of the code is not what I am looking for.
#include <iostream>
usingnamespace std;
string functionOne(){
string array[] = {"H", "E", "L", "L", "O"};
int size = sizeof(array)/sizeof(string);
for (int i = 0; i < size; i++){
return array[i];
}
}
int main (){
string savedArray [5];
for (int i = 0; i < 5; i++){
savedArray [i] = functionOne();
cout << savedArray[i] << " ";
}
return 0;
}
// Given output: H H H H H
// Expected output: H E L L O
I'll take a shot at my mistakes, I guess the problem is returning the array.
for (int i = 0; i < size; i++){
return array[i];
}
is the same as return array[0];, as when i = 0, you will exit the function, returning "H". To make it return whichever character you want, you'd need to parameter which is the index of the character you want. For example,
1 2 3
string functionOne(int index){
// ...
}
Also, a string is an array of characters, so you could just do this:
@integralfx, my guess was right about my mistake. Well, I thought as the loop incremented each time using i++, then the value of array[i] would have returned, but this is not true, and as you mentioned above return statement takes place only once and exits then.
My question is: Is there any way we can send each character individually to a newly built array in the main function, and then make it print out each letter?
My question is: Is there any way we can send each character individually to a newly built array in the main function, and then make it print out each letter?
I don't quite understand what you mean by that. Could you provide an example demonstrating this?
string savedArray [5];
for (int i = 0; i < 5; i++){
savedArray [i] = functionOne(); // Does this send every character ?
cout << savedArray[i] << " ";
}
char functionOne(int index){
// check the range of index
staticconst string array = {"HELLO"};
return array[i];
}
string savedArray [5];
for (int i = 0; i < 5; i++){
savedArray [i] = functionOne(i); // Does this send every character ?
cout << savedArray[i] << " ";
}
// Example program
#include <iostream>
#include <string>
usingnamespace std;
string functionOne(int index){
// check the range of index
string array []= { "H", "E", "L", "L", "O" };
return array[index]; // Return the string at the index.
}
int main(){
string savedArray [5];
for (int i = 0; i < 5; i++){
savedArray [i] = functionOne(i);
cout << savedArray[i] << " ";
}
}
output: H E L L O
The key to this problem was to use
savedArray [i] = functionOne(i);
, so each time index i goes to the function and brings back the necessary string at that index until it reaches the maximum limit 5.
However, if I am allowed to input, then using getline(cin, stringName) is a much easier option.