In my Introduction to C++ classes, we were asked to write a function that returns the length of a string using pointers. The code that I wrote (see full code below) seems to work just fine, but here's the thing I don't understand.
I would think typing 'Yes' followed by Ctrl-Z ( I'm using Windows 10) in the console would stop the input. However, after pressing Ctrl-Z -> Enter the console still waits for further input. I have to start a new line after 'Yes', press Ctrl-Z and then hit Enter again to stop the input.
Why is this the case? Is there a way to stop the input after pressing just Ctrl-Z without any of the two new lines?
I read several posts on cin here, including this, this, and this, but they don't seem to answer my question.
#include "pch.h"
#include <iostream>
using namespace std;
unsigned strlen(const char *str)
{
int count = 0;
while (*str != '\0') { str++; count++; }
return count;
}
int main()
{
char str[100] = {};
char *pchar;
pchar = str;
while (cin >> *pchar) pchar++;
pchar = str;
cout << '\n' << strlen(pchar);
return 0;
}
char *
in C++. Ever. Nor should you be doingstrlen()
by hand (a.k.a. "reinventing the wheel"). I know you probably cannot change any of that; I am just voicing my sadness that so many "Intro to C++" courses out there are still "C (with classes)". This is doing both you and C++'s reputation a disservice. – DevSolarchar *
-- all of which is unnecessary / bad C++ style, and which you will have to un-learn once you get to "real" C++. Instead of showing you<string>
and references and having you do real stuff instead of reinventing the (C) wheel. I feel this is wasting your time, and making things unnecessarily difficult for you (and the instructor). – DevSolarstd::string
and the corresponding functions operating on those. Just two counterquestions: What happens, in your code, if the user enters the 101st character without ending the input? What happens if, e.g. by input redirection, the user enters a null byte somewhere in his input? Also, you can't teach C strings a.k.a.char[]
without teaching pointers as well... which IMHO shouldn't be taught in an intro to C++, at all. – DevSolar<algorithm>
, polymorphy and templates to their full potential instead of worrying about what's under the hood. That's for the advanced course, "library development"... – DevSolar