我正在尝试测试字符串中的字符是否为空格,但我感到非常沮丧:
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;
}
}
我没有收到任何错误,而且我在网上查看过,但不同论坛上的人都说这是测试空间的方法。呃。
最佳答案
当你说
cin >> my_string;
您正在接受格式化输入。 std::cin
丢弃该行中的任何空格,它读取并只产生一个单词。
试试看
std::string my_string;
std::getline(std::cin, my_string);
得到一行,或者
#include <iterator>
// ...
std::string my_string((std::istreambuf_iterator<char>(std::cin)),
std::istreambuf_iterator<char>());
将文件结束标记之前的所有内容都放入字符串中。
关于c++ - 测试字符串中的空格字符...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5877960/