0

Is it possible to have a variable number of string arrays?

psuedo-psuedo code example:

cout<<"Number of family members?"<< endl;
cin>> n;

n_1[5]= {whatever}
n_2[5]= {whatever}
n_3[5]= {whatever}
n_4[5]= {whatever}
n_5[5]= {whatever}
n_n[5]= {whatever}

Is that at all possible?

11
  • 8
    You're limited to 1 string array, 1 global variable and 1 arithmetic operation per C++ program. Commented Feb 4, 2013 at 22:10
  • @LuchianGrigore is that totalitarian c++? Commented Feb 4, 2013 at 22:11
  • 5
    @thang: Totalitarian C++ is normally called Java. This would be draconian C++. Commented Feb 4, 2013 at 22:12
  • What is n_... supposed to represent? What is {whatever} supposed to represent? Provide more details about what you actually want. Commented Feb 4, 2013 at 22:16
  • @RemyLebeau The "n" is supposed to represent the number of family members; the n_... is supposed to represent a string array made for each family member from 1 to n. I hope I am being clear, sorry. Commented Feb 4, 2013 at 22:21

3 Answers 3

5

Your question isn't entirely clear, but it sounds like what you probably want is something on this general order:

std::cout << "Number of family members? ";
std::cin >> n;

std::vector<std::string> family(n);    

for (int i=0; i<n; i++) {
    std::cout << "Name[" << i << "]: ";
    std::cin >> family[i];
}
Sign up to request clarification or add additional context in comments.

6 Comments

Is that creating n character strings for the user (so he/she can put each family member into their own string? I am not familiar with std::vector syntax, I am only a beginner trying a challenge problem; sorry :(
@Chase: Yes, that's creating a vector of as many strings as the user enters (as n).
Thanks! Also, what does placing "std::" in front of cout and cin accomplish?
cout and cin are located in the std namespace. std::cout tells the compiler that cout can be found in std. As an alternative, before using it you can do using std::cout;.
So, I wouldn't need to place it in front of cout or cin? Does using namespace std; perform the same thing?
|
2

Assuming you want to specify the number of these arrays of strings at runtime, you could have a vector<string> or a vector<vector<string>>, depending on what exactly you mean by "string arrays".

Comments

0

If you're doing it in MS Visual studio, then u can just write "using namespace std;" instead of writing "std::" everywhere. I don't know if it works in other IDEs or not, because I'm new in C++ too. Sorry for offtopic :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.