fpiro07
fpiro07

Reputation: 927

C++ getline() doesn't end input

string str, temp;

string c;

cout << "Insert the character that ends the input:" << endl;

getline(cin, c);

cout << "Insert the string:" << endl;

getline(cin, str, c.c_str()[0]);

I should be able to put into the string "test" a string until I digit the ending char but if I enter a double new line it doesn't recognize the ending char and it doesn't end the input.

This is the output:

Insert the character that ends the input:
}
Insert the string:
asdf

}
do it}
damn}

Upvotes: 1

Views: 2431

Answers (2)

Mr.C64
Mr.C64

Reputation: 43044

You may want to redesign your code a little bit, e.g. if the delimiter is a character, then why reading a string (and using a kind of obscure syntax like "c.c_str()[0]" - at least just use c[0] to extract the first character from the string)? Just read the single delimiter character.

Moreover, I see no unexpected results from getline().

If you try this code:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << "Insert the character that ends the input: " << endl;  
    char delim;
    cin >> delim;

    string str;   
    cout << "Insert the string: " << endl;   
    getline(cin, str, delim);

    cout << "String: " << str << endl;
}

the output is as expected, e.g. the input string "hello!world" is truncated at the delimiter "!" and the result is just "hello":

C:\TEMP\CppTests>cl /EHsc /W4 /nologo /MTd test.cpp
test.cpp

C:\TEMP\CppTests>test.exe
Insert the character that ends the input:
!
Insert the string:
hello!world
String:
hello

Upvotes: 1

Pradheep
Pradheep

Reputation: 3819

Change the code to

getline(cin, str, c[0]);

Upvotes: 0

Related Questions