Problem receiving a string with space(s)

closed account (1wqDSL3A)
Hello, here's the code:

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
#include <iostream>
#include <string>

int number;
std::string text;

void Syf(std::string one, int two)
{
    std::cout << one << std::endl << two;
}

int main ()
{
    std::cout << "helloez\n";

    std::cout << "type in a number: ";
    std::cin >> number;

    std::cout << "type in a text: ";
    getline(std::cin, text);

    std::cout << number << " + 2 " << "= " << number + 2 << std::endl;

    Syf(text, number);
}


when i try to read a string variable with a space at getline(std::cin, text); there is no string whatsoever. When i use the standard std::cin only the first word before space is displayed.

Any suggestions?
Janek566
You need cin.sync(); on line 18
The problem is that line 17 only reads in the number part of what you type in and not the end-of-line character that gets inserted when you hit the return (or Enter) key. Then when you come to read in your string it sees the end-of-line character and reads it as an empty line into your string rather than waiting for you to type something else in.

try this:
1
2
3
4
5
6
    std::cout << "type in a number: ";
    std::cin >> number;
    std::cin.ignore(); // skip over end-of-line character

    std::cout << "type in a text: ";
    getline(std::cin, text);


closed account (1wqDSL3A)
ignore worked sync did not. Thank you for your answers im gonna look more into the subject :P
One more thing: this was done on linux with g++. I did the same thing on windows on vc++. It worked then. Is there a difference in these compilers documentation on getline?
Last edited on
Topic archived. No new replies allowed.