hello, there...
how would you send a signal to end this loop
string s;
int counter;
while(cin >> s){
counter++;
} thanks...
Quick answer for : if you are running the program interactively you can send an EOF from the terminal to stop the loop — Ctrl+D on Unix/macOS (when the input buffer is empty) or Ctrl+Z then Enter on Windows. As suggested, a sentinel value (a special word like "quit") is an easy in-program way to stop reading.
Here is a simple pattern that reads whole lines, counts them, and stops on a sentinel:
#include <iostream>
#include <string>
int main() {
std::string line;
int counter = 0;
while (std::getline(std::cin, line)) {
if (line == "quit") break; // sentinel
++counter;
}
std::cout << "count = " << counter << '\n';
} Notes and tips: use std::getline when you need full lines (spaces preserved); operator>> reads tokens and skips whitespace. Initialize counters (e.g., int counter = 0) before using them. EOF is produced automatically when reading from a file or pipe; to simulate EOF in code for tests you can set the stream state with std::cin.setstate(std::ios::eofbit) and use std::cin.clear() to reset it. Finally, check the stream state (e.g., if (!std::cin)) if you need to distinguish EOF from other input errors.
Jump to Post— Killer_Typo 82determins what you are looking for.
since you have String s you can say if s == what i am looking for
break;
that will terminate the loop and continue.
so
while(cin >> s) { if (s == "what i want") break; count++; …
determins what you are looking for.
since you have String s you can say if s == what i am looking for
break;
that will terminate the loop and continue.
so
while(cin >> s)
{
if (s == "what i want")
break;
count++;
} i was testing something...lol..thanks dude...reputation point for you! :)
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.