while (true)
{
cout << "Please enter a some text: ";
cin.getline( sendbuf, 100, '\n' );
i = i + 1;
if (? = "q") // here i am looking for something that if i press q i should come out of look
{
break;
}
}
I am a beginner and eager to learn more. I want to ask if I can provide some way to terminate this loop by typing char 'q' after typing my all desire strings data.
EDIT my sendbuf is char* sendbuf, so I don't think so using std::string will help me.
Don't use a char array, use std::string
class and you get comparison with ==
for free:
#include <string>
std::string line;
while (true) {
cout << "Enter string: ";
std::getline(cin, line);
if (line == "q" || line == "Q") break;
}
This way the size of the line is not limited to whatever the size of sendbuf
is.
If you later need to send data to a function that expects a char*
, you take the address of the first element ( &line[0]
) or simply call line.data()
. There's also size
member function that returns, you guessed it, the size of the string. You're in no way limited by archaic interfaces that work on C-style char arrays. A string is a char array, after all.
if ( !cin || std::strcmp( sendbuf, "q" ) == 0 ) break;
The obvious solution is to use a std::string
, and put all of your tests in the while
condition:
std::string line;
while ( std::getline( std::cin, line ) && line != "q" ) {
// ...
}
In practice, you'll probably want a more complicated test on line
, probably factored out into a separate function. Similarly, if you always want a prompt:
std::istream&
getLineWithPrompt( std::istream& source, std::string const& prompt, std::string& line )
{
std::cout << prompt;
return std::getline( source, line );
}
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.