1

I am working on a project for my programming class that requires me to work with strings. The program begins by asking the user to input a phrase. Normally I would declare something such as:

    string phrase;

Then I would use:

    getline(cin,phrase);

However, the professor told the class that we aren't allowed to use the string class, we must use only c-based strings. I could be wrong but I believe that c-based strings look something like this:

    char phrase[12] = "hello world";

If this is what my professor means by c-based strings, then I do not know how to input a phrase into them. When I attempt this, the program only stores the first word of the phrase and stops at the first space it sees. For example:

    char phrase[12];

    cin >> phrase;

//input: hello world

    cout << phrase;

//output: hello

Any advice would help and would be greatly appreciated, thank you.

BCRwar1
  • 189
  • 5
  • 21

2 Answers2

4

You need to use cin.getline(var_id, var_length) and not cin >> var_id, which actually stops storing the input in the variable when it encounters a space or a new line.

If you want to know more about cin.getline and what problems its use can cause, you can have a look to this post: Program skips cin.getline()

Community
  • 1
  • 1
nbro
  • 15,395
  • 32
  • 113
  • 196
  • Okay thank you, but how do I come up with the "var_length" if I don't know what the user will type in as the phrase? – BCRwar1 Sep 15 '14 at 20:42
  • 1
    Specify the buffer/array length. Create an array large enough, in your opinion. – nbro Sep 15 '14 at 20:43
  • @BCRwar1 `var_length` is the amount of input that you can accept. The user is allowed to type less than this. This is one of the limitations of using a fixed-sized array rather than the `string` class. – Code-Apprentice Sep 15 '14 at 20:50
  • @Code-Apprentice I have one last question. The next part of the program is a for loop that runs through the phrase one position at a time and stops when it gets to the end of the phrase. Example: for(int k = 0; k < length ; k++ ) { phrase[k]; } I guess my question is, how do I determine length? – BCRwar1 Sep 15 '14 at 21:00
  • It ends when *i >= length*. If you want that the loop ends when the inputted phrase is finished, you could use this loop codition: *phrase[k] != '\0'*, because, remember, any c-string, to be such, has to terminate with a null-terminated character. – nbro Sep 15 '14 at 21:04
1

If you are reading input into a static char array you can use sizeof(charArray) to determine its maximum lengh. But take into consideration that the last symbol will be end of line, so you can read maximum length-1 symbols into this array.

char phrase[12] ;
cin.getline(phrase, sizeof(phrase));