[英]Using cin.get() in a loop to input a string
我想知道是否有一种方法可以在循环中使用 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 变量来确定当前正在读取的字符是否是 '\n' 字符。
我对 getline function 有点熟悉。 但是我不知道如何在使用 getline 时通过字符串中的每个字符单独 go 对它们进行计数。 我希望我说的有道理。 我是编程和 c++ 的新手。
我基本上想确定这些字符('','\n')何时出现在我的字符串中。 我将使用它来确定一个单词何时结束,一个新单词何时开始在我的字符串中。
如果您想阅读整行并计算其中的空格,您可以使用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 将包含所有字符,直到结束行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.