while(*userText) stops at a whitespace

Hi again all.

First of all I wish to apologise for posting so much on this recently - C++ for dummies still isn't clear enough for me...

My current problem is that in a header file I'm writing (for practice purposes) I'm passing the pointer of a char array. What I want is the function to output the string and stop when reaches a null value.

The problem it continues only to the first white space (space bar)...

Here's the code from the header file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

bool inctest (char* userText)
{
    cout << "The text that the user entered is as follows: " << endl;
    while(*userText)
        {
            cout << *userText;
            userText++;
        }

    cout << endl;

    return true;
}


I've even tried it with while(*userText != \0) but this still stops at the first whitespace.

I know I can pass the last character using strlen... but why doesn't this work?

Many thanks for all help!
My guess is that the problem is located somewhere else... Would you mind also showing us the part of the code where your program gets input from the user?
How are you reading user input into the array? If you're using operator>>, you should know that it stops reading when it reaches a whitespace. If you want to include whitespace, look up getline().
Exactly.
Ah - see this is why I love you guys! I just hope that my constant posting doesn't get me banned lol.

Here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    // Now this is for testing passing the variable from
    // the user to the function within the includetester
    // header file
    char userString[128];
    cout << "Now please enter a string: ";
    cin >> userString;

        cout << "The string you've entered is " << strlen(userString) << " long!" << endl;

    bool result = inctest(&userString[0]);

    if(result)
        {
            cout << "The passing to the header file worked!!!" << endl;
        }


    return 0;


As an extra note when I display the variable strlen(userString) it says it's only 4 long! *insert puzzled face*
I thought that it was only the \0 that terminated a char array?

By the way here's the output:

Now please enter a string: This is a string
The string you've entered is 4 long!
The text that the user entered is as follows:
This
Instead of cin >> userString; use getline(cin,userString,'\n');, like filipe suggested.

Just to clarify, \0 is meaningless. You mean '\0', which is a character literal. You can also use just a because '\0' == 0.
Okay!!! That worked!

Okay - so it was a stupid noob mistake to make I apologise. But thank you for your help.

One question remains.

Earlier in my program I use the following:
1
2
int number;
cin >> number;

I seem to find that if you've used cin then you can't use cin.getline() later - it just goes straight through.
What ways around this are there?

Thanks filipe - that clicks now. Got it, many thanks
Last edited on
cin >> number; leaves a newline character ('\n') in the input buffer. If you call getline after that, it 'sees' that '\n' and assumes you've typed nothing and pressed enter. To fix this put cin.get(); after cin >> number; to get rid of the newline character.
Yup - works like a treat now.

Can you use 2 cin.getline()'s in one program? Or does that trip? When I've been trying it to kick that last bug out I got a few errors originating from the istream file!
Would it be that getline leaves the '\n' in the buffer as well?

Again thanks for help all.
Would it be that getline leaves the '\n' in the buffer as well?

No, getline gets rid of the newline character. This means that you can safely make as many successive getline calls as you want without worrying about this issue.
Hmm,

Okay, so I've got the cin followed by the cin.get() to clear out the null character ('\0').
Following that I've used the cin.getline(userString,128) and the whole thing compiles and works.
But due to my tampering nature - and a desire to fully understand C++ - should I add a further cin.getline(anyvariabletype) then upon compilation I get the following error:

C:\CPP_Programs\Chap01\MacroMayhem\main.cpp||In function 'int main()':|
C:\CPP_Programs\Chap01\MacroMayhem\main.cpp|79|error: no matching function for call to 'std::basic_istream<char, std::char_traits<char> >::getline(int&, int)'|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\i386-pc-mingw32\4.4.0\..\..\..\..\include\c++\4.4.0\istream|597|note: candidates are: std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::getline(_CharT*, std::streamsize, _CharT) [with _CharT = char, _Traits = std::char_traits<char>]|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\i386-pc-mingw32\4.4.0\..\..\..\..\include\c++\4.4.0\istream|409|note: std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::getline(_CharT*, std::streamsize) [with _CharT = char, _Traits = std::char_traits<char>] <near match>|
||=== Build finished: 1 errors, 0 warnings ===|


Any ideas for this?

Hope my questioning isn't annoying anyone...
Don't do this -> cin.getline(userString,128);
If you work with a string object use this format -> getline(cin,userString,'\n');
If you really want to limit the size entered use cin.getline with a char array and then copy that array to your string. Note that when you use cin.getline with a char size limit, if the user enters more chars than that limit, these chars are not discarded, they remain in the buffer.

As for your other question, you can't use getline to get an int. If you take a look here:

http://cplusplus.com/reference/iostream/istream/getline/
http://cplusplus.com/reference/string/getline/

you'll see that no version of getline accepts an int * as a first argument.
Ah well even though I'm calling the variable
userString
it is actually a char string/array.

Would that make a difference at all?
@m4ster r0shi,
Au contraire, the best way to get an int is with getline!
1
2
3
4
5
6
7
8
9
std::string str;
std::stringstream sstrm;
int tmp = 0;

std::cout << "Enter a number: ";
std::getline(std::cin, str);

sstrm << str;
sstrm >> tmp;
@chrisname:
hahahaha :D

@Tset Tsyung:
Let me explain with an example...

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
using namespace std;

int main()
{
    char arr[11];
    string str;

    //getting a string of unlimited size
    cout << "enter a string: ";
    getline(cin,str,'\n');

    cout << "you entered: " << str << endl;

    //getting a string of up to 10 chars long
    cout << "enter a string, up to 10 chars long: ";
    cin.getline(arr,11,'\n');
    //note that getline sets the last element to '\0'

    str=arr;
    cout << "you entered: " << str << endl;

    //let's see how many chars getline read
    //and what's our string's size...
    int chars_read=cin.gcount();
    int str_size=str.size();

    cout << "characters read: " << chars_read << endl;
    cout << "string size: " << str_size << endl;

    //...to determine if there are characters left
    //in the buffer and get rid of them...
    if (chars_read==10 && str_size==10)
    {
        cin.clear();
        while(cin.get()!='\n');
    }

    //...so that this here works ok! :D
    cout << "hit enter to quit...";
    cin.get();
    return 0;
}
Riiiight...

So, just to clarify.

You use cin for integers...

You usecin.getline(variable, limit) for chars...

And finally you use getline(cin,variable) for strings...

Am I BASICALLY right with that? Admittedly I may be over-simplifying here.

P.S. I have tried mixing the above input types with different variable types - but each time I get the old no matching function for call error message - which I believe is what I will get when trying to use functions with the wrong types, correcty?
Use cin.getline(variable, limit) for char arrays, not for chars. Use cin >> (like you do for ints) or cin.get() for chars.
Note: getline() and cin.getline() can take up to three parameters. The third, should you choose to specify it, is a character that when read stops the readout before the newline is reached. This can, in not so many words, be useful.

-Albatross
Last edited on
Topic archived. No new replies allowed.