Code:
1#include <iostream>2#include <cstdio>3 4 using namespacestd;5 6 intMain () {7 8 Char*s;9s =New Char[ -];//space must be allocatedTenCin.getline (s),5); One inti =0; A while(S[i]! =' /'){ -cout<<S[i]; -i++; the } -cout<<endl<<i<<Endl; -Cin.clear ();//Clear is required when the failbit bit is 1, otherwise the subsequent getline read as an empty string - + stringstr; - getline (CIN,STR); +cout<<str<<Endl; AGetline (CIN,STR,'#'); atcout<<str<<Endl; - getline (CIN,STR); -cout<<str<<Endl; - - return 0; -}
Input and output:
(input) slkdsa;34slkd4sa;34 (input) hel#idhelid
Analysis:
There are two getline functions in C + +, one is defined as a global function in the string header file, the function declaration is istream& getline (istream& is, string& str, char Delim) With istream& Getline (istream& is, string& str);
The other is the member function of the IStream, the function declaration is istream& getline (char* s, streamsize N) and istream& getline (char* s, streamsize N, Char del IM); Note the second getline is to store the read string in a char array without declaring the parameter as a string, because the C + + compiler cannot perform this default conversion.
getline function Approximate flow:
1, first determine whether the IStream failbit bit is 1, 1 words means that the state of the input stream has errors, then do not read operation, getline function End execution
2. From the current position, read a single character sequentially from the input stream and copy it to the buffer until the following conditions are met, and the loop ends.
(1) Stop the read operation when the end of the file is encountered and set the ending tag of the stream object to 1
(2) When the delimiter specified by the caller is read, the character before the delimiter is copied to the buffer, but the delimiter itself is not copied, and the next read operation begins with the next character after the delimiter.
(3) The n-1 character has been read (n is the initial value of the second argument _count passed in by the caller), at which point the Stream object's error flag position 1
Continuous reading with Getline until the end of the text
1#include <iostream>2#include <cstdio>3 4 using namespacestd;5 6 intMain () {7 8 strings;9 while(Getline (cin,s)) {Tencout<<s<<Endl;; One } A - return 0; -}
The use of Getline functions in C + +