在循环中使用 cin.get() 输入字符串

  • 本文关键字:字符串 get cin 循环 c++
  • 更新时间 :
  • 英文 :


我想知道是否有一种方法可以在循环中使用cin.get((函数来读取可以由多个单词组成的字符串。

例如

while (cin.get(chr)) // This gets stuck asking the user for input
while (cin.get(chr) && chr != 'n') // This code doesn't allow the 'n' to be read inside the loop

我希望能够读取整个字符串,并能够使用我的chr变量来确定正在读取的当前字符是否为""字符。

我对getline函数有点熟悉。但是我不知道有什么方法可以在使用 getline 时单独遍历字符串中的每个字符,同时对它们进行计数。我希望我说的是有道理的。我是编程和 c++ 的新手。

我基本上想确定这些字符('',''(何时出现在我的字符串中。我将使用它来确定一个单词何时结束,一个新单词何时在我的字符串中开始。

如果你想阅读一整行并计算其中的空格,你可以使用 getline。

std::string s;
std::getline(std::cin, s);
//count number of spaces
auto spaces = std::count_if(s.begin(), s.end(), [](char c) {return std::isspace(c);});

std::getline将始终读取,直到遇到n

您可以尝试以下操作:

using namespace std;
int main() {
char ch;
string str = "";
while (cin.get(ch) && ch != 'n')
str += ch;
cout << str;
}

字符串 str 将包含所有字符直到结束行。

最新更新