Delimiters such as carriage return and space in scanf and cin in C/C++

The input stream cin will ignore delimiters such as tab, space, and carriage return under any circumstances, including but not limited to cin>>int, cin>>char, , cin>>stringetc.

The scanf function will not read scanf("%c",&char)carriage returns as input characters in the input buffer in all cases except that it scanf("%c",&char)will not read tabs and spaces, but ignore them as delimiters in the input buffer.

So how to enter a string with spaces?
C++:

(1)getline(istream &is , string &str , char delim)

Among them, istream &is represents an input stream, such as cin;

string&str means to store the string read from the input stream in this string (you can name it yourself, str or anything);

char delim means stop reading when this character is encountered. If it is not set, the system defaults to this character as '\n', which is a carriage return and line feed (stop reading when a carriage return is encountered).

(2) cin.getline(character pointer (char*), number of characters N (int), terminator (char));

This function reads multiple characters (including whitespace) at once. It uses the specified address as the position to store the first read character, and stores the read characters in turn until N-1 characters are read, or the specified terminator is encountered. If no terminator is specified, the default terminator is '\n'.

getline() discards newlines, while get() keeps newlines in the input sequence

C:

(1) Using the format character "%[]", its function is to scan the character set. scanf(“%[^c]”,str);where "c" is a specific character constant (including control characters). When entering a string, the character "c" will be used as the terminator for the current input. Using this format character, the programmer can specify an input terminator by himself.

void main() 
{ 
    char* msg = NULL;
    msg = (char *)malloc(100 * sizeof(char));
    scanf("%[^\n]", msg);      // \n作为字符串输入的结束符
    printf("%s", msg);
    return 0;
} 

(2) Use the gets function, the gets function uses the carriage return as the terminator

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325618354&siteId=291194637