Reputation: 593
I'm trying to test if a character in a string is a space, and I'm getting extremely frustrated:
string my_string;
cin >> my_string;
for (int i = 0; i < my_string.length(); i++)
{
if (my_string[i] == ' ') // this never becomes true...
{
cout << "this text should pop, but never does" << endl;
}
}
I'm not getting any errors and I've looked online, but people on different forums say this is how to test for a space. Uh.
Upvotes: 1
Views: 359
Reputation: 6480
Thats because cin stops reading at the first whitespace so you never actually read the entire sentence but the first word. Use getline instead.
std::string my_string;
std::getline(std::cin, my_string);
for (int i = 0; i < my_string.length(); i++)
{
if (my_string[i] == ' ') // this never becomes true...
{
std::cout << "this text should pop, but never does" << std::endl;
}
}
Upvotes: 5
Reputation: 79185
Additionnally to test whether a space is present use std::string::find
!
std::string my_string;
std::cin >> my_string; // please do not use « using namespace std; » if possible
size_t space_position = my_string.find(' ');
if(space_position != std::string::npos)
{
std::cout << "found space" << std::endl;
}
Upvotes: 2
Reputation: 58677
when you say
cin >> my_string;
you are taking formatted input. std::cin
discards any whitespace in that line, and it reads up to and yields only a single word.
try instead
std::string my_string;
std::getline(std::cin, my_string);
to get a single line, or
#include <iterator>
// ...
std::string my_string((std::istreambuf_iterator<char>(std::cin)),
std::istreambuf_iterator<char>());
to get everything up to an end-of-file mark into the string.
Upvotes: 8