Narue 5,707 Bad Cop Team Colleague

a code in 'Let Us C' by Y.Kanetkar confused me since i am only a beginner

A lot of people mistakenly use %u to print the value of a pointer. The correct method is using %p and casting non-void pointers to void:

printf("Original address in x = %p\n", (void*)x);
printf("Original address in y = %p\n", (void*)y);
printf("Original address in z = %p\n", (void*)z);

there seem to be a lot of errors in the book

From a cursory reading of that book, it's total crap. You'll probably learn more bad habits than good ones.

Narue 5,707 Bad Cop Team Colleague

Can you please RTFM?

Moschops commented: Harsh but fair :) +7
Narue 5,707 Bad Cop Team Colleague

I'm digging this change. It's small, but solved threads are much more visible now. :)

Narue 5,707 Bad Cop Team Colleague

because Narue said "where an array is not converted to a pointer to its first element."..

It was a side note only. The general rule is that when an array is used, it's converted to a pointer to the first element. That's why things such as the following are allowed:

int a[10];
int *p = a; // No need to explicitly say &a[0]
void foo(int *p);

int a[10];

foo(a); // Fine, a and p are compatible types here
int a[] = {1,2,3,4,5};

cout << *(a + 2) << '\n'; // Non-modifying pointer arithmetic is OK

These are all value contexts, you're interested in the elements rather than the array object as a whole. Most uses of arrays fall under value context, which is why you'll occasionally hear confused programmers say that arrays and pointers are the same. That's because most of the time they can be used as if they were the same. However, there are three object contexts, where you truly do want to work with the array object rather than its elements (cases where arrays and pointers are not the same):

  • As an operand to the address-of operator (&). You want a pointer to an array, not a pointer to a pointer to the first element:
    int a[10];
    int (*p)[10] = &a; // Correct
    int **p = &a; // Incorrect, incompatible types
  • As an operand to the sizeof operator. You want the size of the array in bytes, not the size of a pointer:
    
           
NP-complete commented: useful info...:) +5
Narue 5,707 Bad Cop Team Colleague

malloc() and free() are declared in <stdlib.h>, you failed to include that header.

Narue 5,707 Bad Cop Team Colleague

I'm really in to C++ now, and just started making a text based game. I want to buy a book, but I'm not sure which one I should buy. I'm up to about part 40 in this series of tutorials. What would you recommend?

I'd recommend reading this thread rather than replying to it with questions that are answered already.

Narue 5,707 Bad Cop Team Colleague

It's no different from if you used an array. Say the array has 10 characters and you type "abcd". The array will contain those four characters, plus a newline and a null character, which means the last four elements will be garbage unless you went out of your way to initialize them:

#include <ctype.h>
#include <stdio.h>

int main(void)
{
    char buf[10];
    size_t i;
    
    /* Initialize to predictable garbage */
    for (i = 0; i < 10; i++)
        buf[i] = '~';
    
    printf("Enter 4 characters: ");
    fflush(stdout);
    
    if (fgets(buf, sizeof buf, stdin) != NULL) {
        for (i = 0; i < sizeof buf; i++) {
            if (isprint(buf[i]))
                printf("'%c'\n", buf[i]);
            else
                printf("[%d]\n", buf[i]);
        }
    }
    
    return 0;
}

Your memory will work the same way with malloc().

Narue 5,707 Bad Cop Team Colleague

so will unused memory contain null characters?

Not when allocated by malloc(). The unused memory will remain uninitialized.

vedro-compota commented: +++ +3
Narue 5,707 Bad Cop Team Colleague

but if i need to apply that in my work, how can i do it ??

Generate the numbers, then shuffle them randomly. For example, see this thread, or this thread.

Narue 5,707 Bad Cop Team Colleague

especially this (may be it's bug) =

block  = ok +block -result -1;

Looks like a bug to me. Addition of pointers is both nonsensical and illegal in C. I see what the author was going for, but it seems especially awkward. I'd rather just keep a running count of the string length and set block to the current null character on each iteration. It's much simpler that way:

char *simple_readline(void)
{
    const size_t block_size = 5;
    
    char *result, *block, *temp;
    size_t size = block_size;
    size_t n = 0;

    result = block = (char*)malloc(size);
    
    if (!result)
        return NULL;
    
    *result = '\0';

    for (;;) {
        if (fgets(block, block_size, stdin) == NULL)
            break;

        n += strlen(block);
        
        if (result[n - 1] == '\n')
            break;

        size += block_size;
        temp = (char*)realloc(result, size);
        
        if (temp == NULL)
            break;

        result = temp;
        block = result + n;
    }

    if (result[0] == '\0') {
        free(result);
        result = NULL;
    }

    return result;
}

If the result is null

result will never be null on the bolded lines. Prior to the loop, result is initialized using malloc(), and there's a test for failure which returns from the function. Inside the loop, result is never reset if realloc() fails.

(why do we need
next piece ) =

if (!(*result))
{
    free( result );
    result = NULL;
}

If result[0] is '\0' then that means the first call to fgets() failed. Rather than risk that case being mistaken as any kind of success (a successful call will …

vedro-compota commented: you're > than "great man" Narue) so many help/// +3
Narue 5,707 Bad Cop Team Colleague

actually i feel the member needs to know the feedback so he can be on the same line with the moderators even if the moderators don't agree to his point.

I agree with you in principle. Since the mods are more intimately familiar with the rules, knowing the decision made on a report could go a long way toward sharing that familiarity. However, as already mentioned, there's a matter of practicality. I don't think it would be fair to ask the mods to provide resolution details to reporters for every report, though we do keep a paper trail of actions and reasons, so if you want to ask how any of your reports was handled and why, don't hesitate to shoot one of us a PM.

This would also help to let the member know what is expected of him before he can flag a post as bad.

Don't be afraid to flag any post as bad, for any reason. It's not very time consuming to look at a bogus report and mark it as ignored, and I'd much rather get false positives than let legitimate bad posts go unnoticed.

Netcode commented: agreed +0
Narue 5,707 Bad Cop Team Colleague

This forum was designed to let lots of people of many different abilities and backgrounds gain advice and experience from other people who are either more advanced or work in different fields.

Funny, I thought the Geeks' Lounge was for chatting about anything. :icon_rolleyes:

It was not designed for people who may or may not be more advanced in programming and development to try and make people feel bad about themselves whilst simultaneously boosting a pathetic forum posters shattered ego from a complete lack of social credibility. I would suggest you take a while to reflect on the sort of person you are and whether you are actually an asset to this forum.

The hypocrisy is strong with this one.

Netcode commented: me too +0
Narue 5,707 Bad Cop Team Colleague

It means you should declare a function before using it.

Narue 5,707 Bad Cop Team Colleague

Visual C++ 2010 Express, Code::Blocks (MinGW's gcc), and Pelles C are all good.

vedro-compota commented: ++++++++++++ +3
Narue 5,707 Bad Cop Team Colleague

Is there a way to do this in c?

In standard C, the short answer is no. The long answer is that you can do it with a lot of fuss and bother, but ultimately it isn't worth the effort for a weak facsimile of function overloading. The alternative answer is if you're willing to sacrifice the full behavior of overloading (ie. the correct function body is magically chosen), you can make a variant type using unions or use variable argument lists to hack something reasonably close to the end result. Once again, it's overly complicated for the minor convenience you get.

If you really want this behavior and your compiler supports overloading as an extension, that's the direction you should go.

Also, the next C standard has a feature in the works that would theoretically accomplish what you want:

#define lala(x) _Generic((x), adktis*: lala_a, kdktis*: lala_k)(x)

Not that it helps you now, of course. ;)

gerard4143 commented: For the psychic poster +13
Narue 5,707 Bad Cop Team Colleague

Basically the time old question of who would win.

Including the time old mistake of no context. Language comparisons without context are pointless.

sureronald commented: agree! +0
Narue 5,707 Bad Cop Team Colleague

Are you really running DOS, or just a simulated DOS in Windows? Anyway, it's the same as Windows: Ctrl+Z.

Narue 5,707 Bad Cop Team Colleague

No, I can figure out the .h and the <> "" thing fine.

Somehow I doubt that.

Just looking for a link where I can download the file from the internet.

And what do you expect to do with the file? It's highly likely to depend on many other files, and be closely tied to the compiler for which it was written. For example, here's the <iostream> contents on my version of GCC:

// Standard iostream objects -*- C++ -*-

// Copyright (C) 1997, 1998, 1999, 2001, 2002, 2005, 2008, 2009, 2010
// Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.

// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along …
Narue 5,707 Bad Cop Team Colleague

Can you explain me that how i[mpg] can return the same value as mpg?

Your book already explains it. mgp[i] becomes *(mpg + i) , and because addition is commutative you can change the order of the operands without affecting the result. Thus, i[mpg] is to mpg[i] as *(i + mpg) is to *(mpg + i) . It's basic math. :)

AnkurThakur commented: Thanks for resolving my confusion :) +0
Narue 5,707 Bad Cop Team Colleague

Your wish is my command. Welcome. :)

jingda commented: Lol +0
Narue 5,707 Bad Cop Team Colleague

You're approaching this the wrong way, the function needs to recognize both the list type and the iterator type. Or better yet, follow the generic pattern given by the standard algorithms:

template <typename InputIterator>
void printList(InputIterator first, InputIterator last)
{
    while (first != last)
        cout << *it++;
}
cout << "The list contains: ";
printList(mylist.begin(), mylist.end());
Narue 5,707 Bad Cop Team Colleague

and also for the code

int main(void)
{
 int i=0;
    printf("%d",++i + ++i + ++i);
}

why output is 7 ?

It's undefined behavior because you're modifying an object multiple times between sequence points. The output could be anything.

but what about sizeof("A")

It's the size of an array of char initialized with two characters ('A' and '\0'). The underlying type of a string literal is an array, and sizeof works in object context, so this is one of the few places where an array isn't converted to a pointer to the first element.

Narue 5,707 Bad Cop Team Colleague

didn't work my man

My apologies, I assumed you were competent enough to take the minor snippet change I provided and work it into a complete program. Try this:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string ans1;

    cout << "How are you? ";
    getline(cin, ans1);

    cout << ans1 << '\n';
}
NathanOliver commented: People these days +9
Narue 5,707 Bad Cop Team Colleague

You have two issues. First, the condition should be while (temp2 != NULL) because you want to include the last node in the search. Second, your search loop doesn't update temp2; the loop is infinite. Compare and contrast:

while(temp2 != NULL) {
    if(search == temp2 -> ID) {
        cout << "ID\tName\n";
        cout << temp2 -> ID << "\t" << temp2 -> name << endl;
        decision = 0;
    }
    
    temp2 = temp2 -> link;
}
Narue 5,707 Bad Cop Team Colleague

Is it is the case that the loop itarates for "N+1" Number of times?

The loop iterates N times, but the statement is executed N+1 times. For example, if N is 0, the loop doesn't iterate but the condition must still be tested. Thus the statement is executed 0+1 times.

In the same manner how can we say

The loop body runs N times. That should be obvious.

Narue 5,707 Bad Cop Team Colleague

The author of this thread clearly stated that you should give a definition in your own term and we still have posts redirecting us to wikipedia.

The author of this thread also doesn't seem to understand that there are many acceptable definitions and Wikipedia covers them sufficiently well. There's no need to reiterate in different words what Wikipedia already says.

Narue 5,707 Bad Cop Team Colleague

The compiler is right, LINE_MAX doesn't exist unless it's a library extension. I'd suggest the standard BUFSIZ, but that still won't work either because your code is severely broken. You're working with uninitialized pointers.

vedro-compota commented: +++++++ +3
Narue 5,707 Bad Cop Team Colleague

You could use an associative container, such as a map, that has unique key values (in your case integers).

Unless N is likely to be very large (I wouldn't bet on it), the brute force approach would be simpler and probably more efficient:

#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>

int main()
{
    std::srand((unsigned)std::time(nullptr));
    
    int n;
    
    std::cout << "Enter N: ";
    
    if (std::cin >> n) {
        std::vector<int> v(n);
        
        while (std::any_of(v.begin(), v.end(), [](int x) { return x == 0; }))
            ++v[std::rand() % n];
            
        for (std::vector<int>::size_type i = 0; i < v.size(); i++)
            std::cout << i << ": " << v[i] << '\n';
    }
}

Of course, this is given my reading of the requirements which suggests that the OP wants to display the random number generator's distribution pattern.

Narue 5,707 Bad Cop Team Colleague

Your syntax is unfortunately wrong, and is not C++.

It's C++, just pre-standard C++.

A long time ago, before C++ was standardised, it was just questionable, but now it's wrong.

Not that long ago. :icon_rolleyes: Besides, if you look at it without the pre-standard hatred, the only questionable part is implicit int on main(). While implicit int was inherited from C and supported in pre-standard C++, it was well known for quite some time that taking advantage of it was poor practice. So stylistically it's questionable, but technically correct.

This should not work, as cout lives in the std namespace.

It works fine with <iostream.h> because namespaces weren't included yet. But once you change the header to <iostream>, then it should fail to compile.

If your compiler accepts your code, it is doing you a disservice and not telling you that you're making mistakes.

Or it's just a pre-standard compiler (can we say Turbo C++?). In those cases, standard code is incorrect because it won't compile, and not everyone can get a newer compiler. Perhaps it's you doing the disservice by being so intolerant. ;)

By all means inform people of the differences between pre-standard and standard C++, as well as the fact that pre-standard features are quickly being phased out (eg. modern compilers are removing support for <iostream.h>), but you can do that without treating pre-standard C++ like heresy.

Fbody commented: Well said. And very tactfully too. +13
Narue 5,707 Bad Cop Team Colleague

What is meant by STEP-COUNT METHOD?

You define what a "step" means for the algorithm (usually statements), then the total of those steps using variables such as N can be calculated.

What is the procedure in that to calculate?

  • First define steps:
    int mean(int a[], size_t n)
    {
        int sum = 0;                 // 1 step
        for (int i = 0; i < n; i++)  // 1 step
            sum += a[i];             // 1 step
        return sum;                  // 1 step
    }
  • Next determine the frequency of the steps based on N:
    int mean(int a[], size_t n)
    {
        int sum = 0;                 // 1 step * 1
        for (int i = 0; i < n; i++)  // 1 step * (N+1)
            sum += a[i];             // 1 step * N
        return sum;                  // 1 step * 1
    }
  • Add up the steps: 1 + (N+1) + N + 1
  • Reduce: 2N + 3
  • Throw away factors that don't grow with N and you're done: O(N)
Narue 5,707 Bad Cop Team Colleague

it is written by the best programmers of the world

The first thing on that page is (emphasis added by me):

This book "A to Z of C" is compiled and written by simple guys who are not experts and who are not native English speakers. And so, this book might have both grammatical and technical errors.

So if by "best programmers of the world" you mean people who might know slightly more than the target audience, I'd agree. In fact, upon getting to the technical stuff, the book makes an immediate mistake:

main( ) should return 0 or 1

While 0 is a portable return value (the enclosing chapter is about "ANSI"--a more correct term would be "standard"--C), 1 is not portable. The standard return value for failure is an opaque macro called EXIT_FAILURE from <stdlib.h>. Surprisingly, the rest of the information on that section is decent enough, but that's not much of a compliment given the small amount of covered material.

The section on undefined behavior is pretty useless because all it does is make readers aware of undefined behavior and point out a few examples without explaining why they're undefined. That's completely unproductive if the goal is to help readers recognize undefined behavior in real code.

The section on XOR is terrifying.

The section on "string function[sic]" is rather pointless as it doesn't explain anything about how those functions should be used. The assumption that showing an implementation of the function alone will …

ProgrammingGeek commented: Wow, how many programming books have you read in your lifetime? +1
Narue 5,707 Bad Cop Team Colleague

Clicky. Pointers are probably "very difficult" not because of any complexity but because you're expecting them to be difficult in your mind. In reality, pointers are both simple and straightforward.

hackit commented: it was really helpfull. +1
Narue 5,707 Bad Cop Team Colleague

I weep for the fall of higher education.

Rashakil Fol commented: Nyahahahahahaha! +0
Narue 5,707 Bad Cop Team Colleague

Do you mind explaining what exactly is happening in that code?

It's extracting the bytes from most significant to least significant by shifting and masking away all but the least significant byte:

01010101111111110000000011110000
00000000000000000000000001010101 -- Shift right 24 bits
                        01010101 -- Mask the low byte

01010101111111110000000011110000
00000000000000000101010111111111 -- Shift right 16 bits
                        11111111 -- Mask the low byte

01010101111111110000000011110000
00000000010101011111111100000000 -- Shift right 8 bytes
                        00000000 -- Mask the low byte

01010101111111110000000011110000
                        11110000 -- Mask the low byte

Each of those bytes are then assigned to a smaller type (uint8_t).

NerdyChick27 commented: Not only did narue help solve something that I've been working for hours, but helped me understand a new concept as well. Thanks! +0
Narue 5,707 Bad Cop Team Colleague

This is a resource with practical leanings. If you want proofs and detailed complexity analysis, a good book on data structures would be your best bet (Robert Sedgewick's Algorithms in C offers good analyses).

Narue 5,707 Bad Cop Team Colleague

I may have a slightly better idea. Instead of making the new thread button more prominent, how about placing a date check script on the reply buttons? If the thread is older than N days, a nuisance popup could be used. The popup would give posters the option of creating a new thread (the default option) or confirming that they really want to reply to an older thread.

Narue 5,707 Bad Cop Team Colleague

mvprintw() takes a variable argument list, not a va_list object. A cursory (pun intended) look at the documentation shows that vwprintw() takes a va_list, but doesn't support the coordinates. So your next step would probably be figuring out how to set the coordinates before a call to vwprintw() as that would produce the desired behavior.

Narue 5,707 Bad Cop Team Colleague

malloc returns the blocks in random way(dynamic)
calloc returns the blocks in sequencial way means one after another
realloc is used to minimise already allocated memory blocks or maximize the same

That's the dumbest thing I've read all morning. But it's early, so I'm sure someone will come up with something better. Now to correct your misconceptions.

malloc returns the blocks in random way(dynamic)

WTF is that supposed to mean? Sure, it might seem random due to the strategies memory managers will use, but I fail to see how that's even moderately useful to you as the end programmer. Each pointer returned by malloc() is unique on success or NULL on failure, and that's all you can assume.

calloc returns the blocks in sequencial way means one after another

malloc() and calloc() are identical with the exception that calloc() initializes the bytes to zero. A logical implementation is thus:

void *calloc(size_t count, size_t size)
{
    size_t total = count * size;
    void *mem = malloc(total);

    if (mem != NULL)
        memset(mem, 0, total);

    return mem;
}

I've seen your mistake before, and it typically stems from the way calloc() separates item count and item byte size while malloc() only takes a total byte count. However, that's only a superficial difference; semantically the effect is the same.

realloc is used to minimise already allocated memory blocks or maximize the same

realloc() does one of three things:

  • Simulate malloc() if the first argument is NULL.
  • Simulate …
WaltP commented: yeah, and it's 3.5 years after the fact, too. +17
Narue 5,707 Bad Cop Team Colleague

You can write a few non-member friend operators with arguments covering the different cases:

class Element {
    double number;
public:
    Element(double init): number(init) {}

    friend Element operator+(const Element& lhs, double rhs);
    friend Element operator+(double lhs, const Element& rhs);
    friend Element operator+(const Element& lhs, const Element& rhs);
};

Element operator+(const Element& lhs, double rhs)
{
    return Element(lhs.number + rhs);
}
 
Element operator+(double lhs, const Element& rhs)
{
    return Element(lhs + rhs.number);
}
 
Element operator+(const Element& lhs, const Element& rhs)
{
    return Element(lhs.number + rhs.number);
}

By the way, allocating memory with new and then returning the dereferenced object is just begging for a memory leak.

fruitymo commented: Thank you :-) as for my memory leaks, will take care of it and check them using Valgrind. +1
Narue 5,707 Bad Cop Team Colleague

Why would absolute beginner, that does not know how to use rand(), use vectors?

What's wrong with vectors? I assume you're suggesting that arrays be used instead, which is silly. C++ doesn't have to be learned from the bottom up. In fact, learning C++ with an eye toward realistic code (using available libraries to make things easier) is generally a better approach for two reasons:

  1. Beginners can start writing powerful code much sooner. There's a lot of prerequisite knowledge and experience required to simulate what std::vector does versus simply using std::vector from day one.
  2. Many of the lower level aspects of C++ are both unnecessary and also unnecessarily complex for a beginner.

I was programming C++ for a year and a half now, and I just learned what vectors are a month ago!

So? All this implies is that you've ignored the more useful parts of the standard library for far too long.

L7Sqr commented: Agreed. 100% +7
Narue 5,707 Bad Cop Team Colleague

And? What have you done so far? Realize that Daniweb isn't a homework service, we expect you to put forth a certain measure of effort.

Narue 5,707 Bad Cop Team Colleague

You mean highest in order of precedence?

If I meant that, I would have said that. My words were carefully chosen. Think in terms of an expression tree and you'll understand what I meant:

(i = 15) || (j = 29)


         ||

   =           =

 i   15      j   29

Shouldn't we simply follow the precedence order blindly?

No, because precedence isn't the only thing involved. You also have associativity and order of evaluation. In the above example, the order of evaluation is left to right with short circuiting. Parentheses around a sub-expression don't alter the behavior of the parent operator, but they can certainly alter what is viewed as a sub-expression. Consider this:

i = 15 || (j = 29)

Removing parens on the left expression changes things drastically:

i = 15 || (j = 29)


  =

i      ||

    15       =

           j   29

That's the difference in precedence here, not the evaluation order of ||'s sub-expressions. Blindly evaluating everything in parens first and unconditionally is a start, but it's not a perfect guideline. If you don't want to go to the trouble of learning how complex expressions are parsed, just break them down and remove all ambiguity:

int i = 5, j = 10;
int cmp;

i = 15;
j = 26;
cmp = i || j;

printf("%d\n", cmp);
printf("%d %d\n", i, j);

This produces the output you originally expected.

Narue 5,707 Bad Cop Team Colleague

Too late, already made char array tokens

It's never too late to refactor your code into something better.

Narue 5,707 Bad Cop Team Colleague

Stupid questions teaching useless trivia with horrible code examples. I'd appreciate if you didn't propagate the rampant stereotypes of Indian programmers while at the same time leading everyone else astray. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

Why you use this..

printf only uses for printing something.
You may be miss something.

You're the one who's missing something. Since you don't appear to know what you're talking about in the majority of your posts, might I suggest asking questions rather than trying to answer them?

Narue 5,707 Bad Cop Team Colleague

what does it all mean for C/C++?

Nothing at all. C++ will continue chugging along in the areas that it's best suited. People will continue to claim that C++ is dead or dying, and they'll continue to be wrong for the foreseeable future. People will still come up with reasons why C++ should die, and they'll be largely ignored. People will continue to create languages that will be hailed as the "C++ killer", which will continue to find niches while failing to kill C++.

The reality is that languages with any reasonably large source base will never die. Case in point: COBOL. While you don't hear about COBOL because it's not sexy or fashionable, the source base is huge, and if you know COBOL, you can practically write your own paychecks to maintain it.

Narue 5,707 Bad Cop Team Colleague
#include <stdio.h>
#include<conio.h>
int main()
{
  int this_is_a_number;

  printf( "Please enter a number: " );
  scanf( "%d", &this_is_a_number );
  printf( "You entered %d", this_is_a_number );
  getch();
  return 0;

No no no, silly. It should be like this:

#include<stdio.h>
#include<conio.h>

void main()
{
    clrscr();
    int this_is_number;
    printf("enter number");
    scanf("%d", this_is_number);
    printf("you entereded %d", this_is_number);
    getch();
}

You can't be a proper conio noob without also voiding your main(), calling clrscr() unnecessarily at the beginning of every program, compiling as C++ without knowing it, completely ignoring user friendly output, and habitually misusing scanf() (with the claim "it works for me" when challenged). You get bonus points for placing a newline at the beginning of printf() format strings instead of the end, but that's not a requirement.

jbennet commented: narue you are a legend +15
WaltP commented: That'll teach 'em!!! +17
TrustyTony commented: Take care, goddess, not to become fat, eating newbies for breakfast ;) +13
Narue 5,707 Bad Cop Team Colleague

IS THERE ANY WAY FOR THE USER TO ENTER "ENTER" TO FINISH TYPING....

Since you're using getche() to read characters, your loop needs to recognize the first part of a newline. Since you're using Windows, that character would be the first part of a CRLF sequence: '\r'.

#include <iostream>
#include <string>
#include <conio.h>

int main()
{
    std::string line;
    int ch;
    
    std::cout << "Enter a line: " << std::flush;
    
    while ((ch = getche()) != '\r')
        line += (char)ch;
        
    std::cout << "\nYou entered '" << line << "'\n";
}

IS THERE ANY WAY TO REMOVE EXTRA CHARACTERS BY BACKSPACE...

Without the shell to help you, this logic needs to be a part of your code. You need to recognize the '\b' character and act accordingly:

#include <iostream>
#include <string>
#include <conio.h>

int main()
{
    std::string line;
    int ch;
    
    std::cout << "Enter a line: " << std::flush;
    
    while ((ch = getch()) != '\r') {
        if (ch == '\b') {
            if (!line.empty()) {
                line.erase(line.end() - 1); // Update the line
                std::cout << "\b \b";       // Update the display
            }
        }
        else {
            line += (char)ch;
            putch(ch);
        }
    }
        
    std::cout << "\nYou entered '" << line << "'\n";
}

Note that special character handling like this requires that you use getch() rather than getche() to properly manage the display of characters as they're typed. Specifically for backspace, you don't want to display a destructive backspace unless the underlying string also has a destructive backspace.

AND HOW WILL IT SHOW UP IN ASTERISKS... …

Narue 5,707 Bad Cop Team Colleague

Now adding a const in my operator+(PNVector) (i.e. operator+(const PNVector &rhs) fixed this issue and I fail to grasp why.

Long story short, you were trying to bind a temporary object to a non-const lvalue reference (not legal). Temporaries may be bound to a const lvalue reference, which is why adding const fixed the problem.

Narue 5,707 Bad Cop Team Colleague

Q1. What is your name and job profile (like Database Administrator, Programmer etc.)?

List me as anonymous. My job profile is software architect (enclosing all parts of development from requirements gathering to deployment and maintenance). I also act as a consultant for IT and development staff in a wide range of fields.

Q2. How often do you write each day a week?

Very often.

Q3. How important is what you write to the successful performance of your job?

It's critical.

Q4. Is writing important to your promotion/career? How?

I fail to see how this is a different question from Q3.

Q5. What are the different types of writings you do (like names of reports you make, other documents you write)?

Correspondence with clients, partners, and vendors makes up the lion's share of what I write. I also write documentation, training materials, press releases, and such.

Q6. What would be a major fault in a piece of writing in your profession?

Lack of clarity.

Q7. What are the features of writing that you look for in someone’s writing and strive for in your own?

A certain measure of polish that says "professional and trustworthy". Sloppy writing suggests sloppiness in other areas, and being sloppy doesn't help me win any contracts. ;)

anirudh33 commented: helpful and well written +0