简体   繁体   中英

Using cin.get() in a loop to input a string

I was wondering if there is a way of using the cin.get() fuction in a loop to read a string that could be composed of more than one word.

For example

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

I want to be able to read a whole string and be able to use my chr variable to determine if the current character being read is a '\n' character.

I'm a little familiar with the getline function. But I don't know of a way to individually go through every character in the string while counting them when using the getline. I hope what I'm saying makes sense. I'm new to programming and c++.

I basically want to determine when these characters ( ' ', '\n') happen in my string. I will use this to determine when a word ends and a new one begins in my string.

If you want to read a whole line and count the spaces in it you can use 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 will always read until it encounters an \n .

You could try the following:

using namespace std;

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

and the string str would have all characters till end 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM