I'm trying to read a keyboard entry into a 256 char buffer then extract from just the chars entered (trying to restrict it to just 8 characters) I am fundamentally not understanding how the #$%#$^ing char arrays work:

#include <iostream>

using namespace std;

int main()
{

    char buffer[256];
    char pw[8];
    int counter = 0;
    cin >> buffer;

    for(int i = 0; i < 256; i++)
    {
        if(buffer[counter] == '\n')
        {
            break;
        }
        else
        {
            counter++;
        }
    }


    if(counter > 8)
    {
        cout << "too large\n";
        cout << endl<<counter;
    }
    else
    {
        for(int i = 0; i < 8; i++)
        {
            pw[i] = buffer[i];
        }
        cout << "\nPassword "<< pw;
    }

}

Instead of the while stopping at 8 it just goes whole Fing hog. Can someone tell me what's going on?

Instead of the while stopping at 8 it just goes whole Fing hog.

I'm not sure what that's even supposed to mean. "whole Fing hog"... I'm sure you can provide a more productive description then that!

String's in C are null terminated, and cin doesn't read in the newline. Your program can be fixed by changing one letter.

cin >> buffer will auto stop getting keys from the keybord when cin counters the first white apace (space, tab or '\n'). Buffer will never contain any of those white space characters, so your loop on line 13 ill never find one.

If you want buffer to include all white spaces too, then call getline() instead of sin.

cin.getlne(buffer, sizeof(buffer)); But here too buffer will not contain the '\n' characters.

strlen(buffer) will return the length of the string in buffer.

Edited 2 Years Ago by Ancient Dragon

"I'm not sure what that's even supposed to mean. "whole Fing hog"... I'm sure you can provide a more productive description then that!"

I meant instead of what I wanted extracted, it was just throwing up everything in the buffer, I was just being funny, and if it was so unhelpful a post...I was going to say something snarky, but you did indeed solve my problem. So thank you Hiroshe, and I think you've helped me several times before, so big ups to you pal! '\0' not '\n' what a dumb rook mistake. Thanks again.

Ancient Dragon you another well of information, thanks...I ALWAYS learn something from you.

This question has already been answered. Start a new discussion instead.