I’m having some trouble with this code. I am trying to write a function that allows a user to input a string (of multiple words) and then returns the 1st word. A simple task with Python but C++ baffels me yet again. I’m part way there and realize I need to still add the implementation for 1st token but in incremental debugging I’ve run into some snags. Questions I’m after are:
- Why, when I enter integers, does the function print those on the console? Shouldn’t entering ints cause the cin stream to fail and therefore repromt the user for another entry?
- How can I get the window to pause (maybe waiting for an “enter” from the user) before returning? It prints and returns so fast it’s hard to see what it does.
Here’s the code:
/*
* Problem 1: "Extract First String"
* Takes a user string and extracts first token (first token can be a whole word)
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void ExtractFirstToken();
int main()
{
ExtractFirstToken();
return 0;
}
/*
* Trying to create a function that will allow a user to enter a string of words and
* then return the first word
*/
void ExtractFirstToken()
{
cout << "Please enter a string (can be multiple words): ";
string stringIn;
while (true)
{
cin >> stringIn;
if (!cin.fail()) break;
cin.clear();
cout << "not a string, please try again: ";
}
cout << stringIn;
}
because a string is perfectly capable of holding “12345”. Why would it fail?
I’d say something like
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
(heh, amusing that my answer is exactly like Benjamin Lindley’s, right down to using numeric_limits and streamsize)This will wait for input until you hit enter.