Arrays -> Strings with spaces

First off I am a beginner and I am teaching myself C++.

I am using a hotel as my bases and implementing all learned pieces as I go.

The code below functions, but there is a little bug still and I cannot wrap my head around it.

If I enter 3 for the "info" count I will be asked 3 times to enter guest data questions. If I enter single words, the code works, but if I enter multiple words with spaces "First Name", the system jumps forward as there are words in the string.

I assume if I enter three words (with spaces) "My First Name :" it will jump to the forth guest entry right away.

Question is: Why does the space within the string cause each word to be stored in its own array position instead of the whole thing in the first position as intended?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int Guests;
    int GuestInfo;

    cout << "How many guests can your hotel hold?" << endl;
    cin >> Guests;
    cout << "How much info do you wish to store for each guest?" << endl;
    cin >> GuestInfo;

        string signup_questions_arr[GuestInfo]={};

//This is where the signup questions are created!!
    for (int x=1; x<=GuestInfo; x++)
        {
            cout << "Name your guest info Nr. " << x << endl;
            cin >> signup_questions_arr[x];
        }
    for (int x=1; x<=GuestInfo; x++)
    {
        cout << signup_questions_arr[x] << endl;
    }
return 0;
}
Last edited on
> string signup_questions_arr[GuestInfo]={};

This is not conforming C++ code; the size of an array must be a constant known at compile-time.
The GNU (GNU-compatible) compiler will accept this by default, but that does not make it valid C++.

If the number of elements are not known beforehand, use std::vector<>
https://cal-linux.com/tutorials/vectors.html


> for (int x=1; x<=GuestInfo; x++)

Array indices start at zero, not one; and end at N-1 where N is the number of elements.
for ( int x = 0; x < GuestInfo; ++x )

To read a complete line into a std::string, use std::getline()
http://www.cplusplus.com/reference/string/string/getline/
Thanks for the enlightenment JLBorges!
Simple mistake.
In array declaration the elements are 4 but the actual positions are 0-3.

I will study those links and try to get it to work with multiple words for one entry.

Thanks again!

Topic archived. No new replies allowed.