Hello I am currently making a program that reads from a text file and a bunch of questions and answers and puts them on screen for a practice test for my class.
My teacher is lazy and for my ISP had me make a program that he can test future classes with.
anyways I have a class that reads the file and I am having trouble returning the array of strings that I get from reading the file. I have tried making a pointer to the array so that I can access it from my main function but I am having problems.
When I try this it gives me an error.. cannot convert int[3] to *int
which obviously means I cant make a pointer to the array. But I am wondering if I am doing it wrong or there is a different way.
This is just some practice code.. not my program :p
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
usingnamespace std;
int main()
{
int fish[3] = {5,2,3};
cout<<fish[0]<<','<<fish[1]<<','<<fish[2]<<endl;
int *tuna = &fish;
cout<<tuna<<endl;
}
I want to be able to read the array from my main function. when the array was made in a different class. without having to make a for/while loop or returns. and was wondering if this was possible.
is invalid because C++ requires that size of array be a constant expression. You can use such construction provided that your function was declared with constexpr specifier.
As for your problem you can allocate dynamically your array and return a pointer to it. The better approach is to use std::vector<std::ctring> defined in the main and pass it by reference to your function.
it compiles fine and works fine... so its not invalid...
getLine() returns an int. this is the size of the array.
each index in the array represents a line.
The easies way to solve your problem is to use stl collection, such as vector where you can add new element or remove an element.
a simple example for your case ->
int main(){
vector<string> list;
getString(list);
// here you can do whatever you wish with your list of strings
// for instance
for(int i = 0 ; i < list.size() ; i++){
cout<<list.at(i)<<endl;
}
// or use iterator to do other things
}
it compiles fine and works fine... so its not invalid...
It is incorrect C++. Your compiler is not quite a C++compiler and lets it through. It's not necessarily a problem, but you should know when you're coding in C++ and when you're not.