简体   繁体   中英

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}

You may want to redesign your code a little bit, eg 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, eg 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

Change the code to

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

The result is OK. It shouldn't ends the input immediately. It reads until '\\n' and then it stores your input until reading the delimiter.

Delimiter of getline :

The delimiting character. The operation of extracting successive characters is stopped when this character is read. This parameter is optional, if not specified the function considers '\\n' (a newline character) to be the delimiting character.

For example, if your delimiter is # , you input abcd#hello , the result will be abcd .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM