0

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.

1
  • "I will use this to determine when a word ends and a new one begins in my string" - then why not read the input word-by-word instead? That is how operator>> reads by default, ie string word; while (cin >> word) { ... }. Or, if you want to read words in a single line: string line, word; while (getline(cin, line)) { istringstream iss(line); while (iss >> word) { ... }} Commented Oct 14, 2019 at 20:44

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

why not simply auto spaces = std::count(begin(s), end(s), ' ');?
Because there are more characters than ' ' that can be classified as a space. For example a tab. I agree that it might be more than is needed in most cases.
Thanks, I wasn't familiar with the purpose of std::isspace.
"std::getline will always read until it encounters an \n" - or a user-defined delimiter. \n is just the default delimiter
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.