Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a few problems with your loop and this is how I'd rewrite it, keeping it as similar to your implementation as possible:</p> <pre><code>string getName() { bool stop; string name; string::iterator it; do { stop = true; cout &lt;&lt; "enter name: "; getline(cin, name); for(it = name.begin(); it &lt; name.end(); it++) { if( (tolower(*it) &gt; 'z' || tolower(*it) &lt; 'a') &amp;&amp; tolower(*it) != ' ' ) { cout &lt;&lt; "Error, only letters! \n"; stop = false; break; } } cout &lt;&lt; "here\n"; } while (!stop); return name; } </code></pre> <p>With what you had here:</p> <p><code>if(tolower(*it) &gt; 'z' || tolower(*it) &lt; 'a' &amp;&amp; tolower(*it) != ' ')</code></p> <p>Due to <code>&amp;&amp;</code> having higher precedence, it equates to:</p> <p><code>if(tolower(*it) &gt; 'z' ||</code><strong><code>(</code></strong><code>tolower(*it) &lt; 'a' &amp;&amp; tolower(*it) != ' '</code><strong><code>)</code></strong><code>)</code></p> <p>which is not what you want.</p> <p><strong>EDIT:</strong> since <code>' '</code> (space) is <code>&lt; 'a'</code> your code won't actually cause problems, but I'm not sure you did it like that on purpose.</p> <p>I also don't like this: <code>if(it == name.end()-1) { stop = true; }</code>, and a <code>do...while</code> loop is better suited.</p> <p><strong>EDIT:</strong> You might also want to add a check for empty input (all whitespace), since that would seem an invalid name.</p> <p><strong>EDIT(again):</strong> Loki's right, you must have junk on the input stream before calling <code>getName</code>. You can use Mścisław's solution or <code>cin.ignore()</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload