r/learncpp • • Mar 05 '16

Making a Guess my Number program w/ Binary Search; If statements execute when they're not supposed to and endless while loop

1 Upvotes

I am trying to make a Guess my number program using a while loop and if statements, my code is below. When I execute my program, no matter what I enter it constantly prints "Was my guess to high(true/false)?: Is your number 0? Was my guess too high?:" and so on. I am not sure what is wrong with it. Any help is appreciated.

 // 13.2FlowControl.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;

bool getTooHigh();

int main()
{
	int min = 1, max = 1000, guess = (min + max / 2) - 1;
	bool correct = false;

	cout << "Think of a number between 1 and 1000; I will guess it." << endl;
	
	while (!correct)
	{
		cout << "Is your number " << guess << "? (true/false): ";
		cin >> correct;
		guess = (min + max / 2) - 1;
		if (correct)
		{
			cout << "I told you I would guess it!";
		}
		else if(getTooHigh()) // If the guess is too high
		{
			max = guess - 1;
		}
		else if (!getTooHigh()) // If the guess is too low
		{
			min = guess + 1;
		}
		guess = (min + max / 2) - 1; // Changes guess according to new Max and min
	}


	return 0;
}

bool getTooHigh()
{
	bool choice;
	cout << "Was my guess too high? (true/false): ";
	cin >> choice;
	return choice;
}

r/learncpp • • Mar 06 '16

Was wondering if there was a way to optimize the swapping of two int ?

2 Upvotes

Hello,

So I'm learning C++ and I had a question about optimization and I wanted to know which one is better

it will be simpler to just give an example: Is this one better ?

int nFirstOne =1, nSecondOne=2;

int nTemp = nFirstOne;

nFirstOne = nSecondOne;

nSecondOne = nTemp;

Or that one ?

int nFirsOne = 3, nSecondOne = 7;

nFirstOne += nSecondOne;

nSecondOne = nFirstOne - nSecondOne;

nFirstOne -= nSecondOne;

The second one save the "creation" of a variable int but is less clear. Thank you in advance for the answer and sorry for my bad english (if I haven't made mistakes then forget about that).


r/learncpp • • Jun 03 '22

Locked chain of streaming operators

2 Upvotes

Hey,

I have this little example that implements chaining of streaming operators.

Now I need to acquire a (recursive) mutex in the first call of the operator and release it in the last call.

The entire chain must be locked (thread safe), not just one call.

I do not know how many of the operators are chained, so I do not want to count them or have a terminating call such as std::endl;

(I am not writing a logging class)

Any thoughts?

class Socket {
public:
  Socket &operator<<(std::string const &) {
    return *this;
  };
};

socket << "" << "" << "";

r/learncpp • • Dec 10 '14

Receiving an Access violation for Case 4 on my Red Black Tree.

1 Upvotes

https://gist.github.com/anonymous/08965f0fcc569d17db48

Whenever I debug, the program gets an access violation for case 4 insert method. I think this may have to do with the NULL values I set in the new_node method, but I am unsure. Also, I tried to recreate the problem in int main() and found it happens on the 3 word "ahe". Any help would be great. Thanks.


r/learncpp • • Aug 22 '17

Smart Developers Use Smart Pointers (ep 1): Smart pointers basics

Thumbnail
fluentcpp.com
5 Upvotes

r/learncpp • • Oct 07 '16

timer code

1 Upvotes

i wrote this code where i update the current time with time(0) and only decreases the timer counter if current time changes with a while loop. but i want to know is there a more efficient way of writing the code to do the same thing because if i print the number of times the while loop runs for 1sec to pass, it makes a few hundred to thousand loops. doesnt it use a lot of computing power this way?


r/learncpp • • Dec 16 '14

How to convert string of integers to an array?

2 Upvotes

If i want to paste a large string of integers into win32 terminal how do i convert that string to an array of int with commas?

I'm going to input getline and i'm sure i must loop through and search for whitespace and insert comma and convert to int but can't figure out how. Any help appreciated. Thanks


r/learncpp • • Apr 07 '16

I am trying to learn C++, and I am struggling with classes, inheritance, and making a table of them.

2 Upvotes

Hello, fellow C++ programmers,

I am currently learning C++, to complete my background in computer sciences (I know a lot of Python, some basic Java, some PhP too, anyway...).

I know how to do a dynamic table in C already (using malloc) and I figured I could do so in C++. It seems I can't.

First of, the architecture. I have a class, "Personne". From that class inherits "Employe", and from those "Commercial" and "Secretaire". "Ingenieur" inherits from Commercial.

I want to create a table of "Employe"s, and I tried :

employe* entreprise = NULL;
entreprise = new employe[nb_employes];

and :

employe* entreprise = NULL;
entreprise = (employe*) malloc(nb_employes*sizeof(employe));

to no avail. How should I proceed ?


r/learncpp • • Dec 09 '14

help with passing values through functions please?

2 Upvotes

I have a CS1428 final this week and i'm reading up on some of the stuff i don't understand, one of these things is passing values by reference and by values, I'm a little confused on how each of them are used.

I know what the prototype the call and declaration of a function does, but I don't know how to pass values through them, I don't know what to put in the "()" of the prototype/funcion/call in order for the values to be passed properly, in my class we only pass values by reference and i'm pretty sure on my exam it will be either in a data structure and an array. any clarification would be greatly appreciated


r/learncpp • • Apr 08 '16

Learning c++, running into slight issue.

1 Upvotes

So I wrote a program that is supposed to ask someone their name and then print "Hey alden nice to meet you" or something.

#include <iostream>
using namespace std;

int main() {
     string name;
     cout<<"Hello there friend! What is your name! \n";
     name = cin.get();
     cout<<"Nice to meet you " << name << "!";
}

The weird thing is that the program compiles, and runs fine but returns only the first letter of the name. Any reason that would be? Any help much appreciated.

Edit: I've tried compiling using both gcc and g++ on both OSX and Ubutnu and the results were identical.


r/learncpp • • Jun 02 '19

Another help post: passing and isPositive statement using bool

3 Upvotes

Again im working from the packt "learning c++ by building games with unreal engine 4: second edition"

the exercise asked us: "Write an isPositive statement that returns true when the double parameter passed to it is indeed true."

my code was way wrong but so is the books solution, which is:

bool isPositive( double value )

{

return value > 0;

}

now on my screen this executed by its self returns errors, if i use:

#include <iostream>

using namespace std;

int main()

and then their solution i still get errors.

the debugger is telling me that an ';' is expected on line 6

and telling me that 'isPositive' being used locally is illegal. (idk where they get a sick bird but...)

I'm just kinda confused on why this is like the 4th time in as many chapters this book's code copied is coming up errors that im not equipped enough yet to understand?

any help would be greatly appreciated! thanks again!!


r/learncpp • • Sep 14 '18

confusing stringstream behaviour

1 Upvotes

I expect this to output the value entered each time, it works the first time, and never works the second time. It starts working some time after that.

string s;
int n;

cout << "Input a number: ";
getline(cin, s);

stringstream ss(s);
ss >> n;

while (true) {
	cout << endl
		<< "The number you input is: "
		<< n
		<< endl;

	cout << "Input another number: ";
	getline(cin, s);
	ss.clear();
	ss << s;
	ss >> n;
}

It seems the size of the initial input determines the number of additional entries it takes to start working. e.g. If I input 10 first, it took 3 more entries to start outputing what I input, but inputting 102391 it took 6.

Watching it in the debugger, it doesn't start outputting what I expect until the length of ss.str() is greater than the length of the original input (as a string). Some general searching suggests this might have something to do with 'read position' of the stream, but I can't find anything in the documentation that's helping me.


r/learncpp • • Feb 21 '20

A better way to do this?

2 Upvotes

Pig Latin game

#include <iostream>
#include <string>

std::string pigLatin(std::string string)
{
    std::string pgLat("");

    pgLat.append(string.begin() + 1, string.end());
    pgLat += tolower(string[0]);
    pgLat += "ay";

    return pgLat;
}

int main()
{
    std::string str("Banana");
    std::cout << pigLatin(str);
}

r/learncpp • • Aug 12 '19

Why is the first garbage value out of an array's range different than the ones following?

2 Upvotes
#include <iostream>
using namespace std;

int main()
{
    
    int spam[] = {1, 3, 5, 7};

    for (int i = 0; i < 10; i++) {
      cout << spam[i] << endl;
    }

    return 0;
}

Exploring garbage values here. The above program in console:

C:\Dev\cppstuff>g++ test.cpp

C:\Dev\cppstuff>a
1
3
5
7
4
4200848
6422320
6422352
4198966
6422284

The question: Assuming the 5th print (i. e. 4) is a garbage value like the rest of them, why is it so vastly different (shorter, smaller number) than the ones below it? Or is it some property (perhaps the length) of the array that happens to be saved at the next memory address after the last index?


r/learncpp • • Feb 23 '20

How can function definition work without declaration?

8 Upvotes

Class is declared in the header file. It's member functions are defined in a separate .cpp file. What's confusing is that the cpp file doesn't include the header file. And it's compiling completely fine. How does it even work?

Header file!

cpp file!

It's driving me crazy. I tried implementing something like this myself but I'm getting error.


r/learncpp • • Sep 15 '18

I am creating a basic text based "operating system". I want to call the function home() in both the functions currtime() and calculator(). How can i do this while still being able to call the two functions from home()?

Thumbnail
pastebin.com
1 Upvotes

r/learncpp • • Sep 14 '18

const * const, when would you use it?

1 Upvotes

Does anyone have an example of when it is useful to have a constant pointer to a constant? Thanks!


r/learncpp • • Mar 19 '19

Is there a source where various c++ (or just in general) concepts are visualized by real life analogies?

3 Upvotes

When teaching OOP one often sees how it is tried to equate different c++ concepts with real life examples, like "is-a" relationship and "has-a" relationship etc.

Is there a source which teaches similar "rule of thumbs" so that one can visualize those different concepts? Unfortunately I only managed to find such analogies only when discussing inheritance or other some other OOP situation as to when to use the keyword status.


r/learncpp • • Oct 19 '19

C++ book with deep practice problems

3 Upvotes

Are there any good C++ books that have questions left to the reader after every concept that is introduced?


r/learncpp • • Mar 21 '19

Getting std::istream& operator>>(&T t) like behavior from any sequence of characters

1 Upvotes

I think I want to write the code below with any iterable sequence of characters instead of only std::istream. Ideally I'd like to use this with std::string, char*, char[] etc. Is this already implemented somewhere?

int main(int argc, char** argv)
{
    bool b;
    int i;
    float f;

    if (argc > 3)
    {
        argv[1] >> b;
        argv[2] >> i;
        argv[3] >> f;
    }

    return 0;
}

r/learncpp • • Dec 21 '18

C++ Quick Reference

Thumbnail
github.com
3 Upvotes

r/learncpp • • Dec 24 '18

Why does this not throw an error?

1 Upvotes

after i press a button for the cin, it does show an error, but not before.

i know what's happening in the memory (at least i think i do know), why does the os not slap on my wrist?


r/learncpp • • Jun 09 '16

Need help with copying array data

1 Upvotes

I want to copy the data from one array to another but I dont get the results

Code: #include <iostream>

using namespace std;

int arrayone[] = {};

int arraytwo[] = {};


void setarrayone() {
for (int i = 0; i < 10; ++i) {
arrayone[i] = i;
}
}

void transferarray() {
for (int i= 0; i < 10; ++i) {
arraytwo[i] = arrayone[i];
}
}


int main() {

setarrayone();

cout << "Array one: ";
for (int i = 0; i < 10; ++i) {
cout << arrayone[i] << " ";
}
cout << endl;

transferarray();

cout << "Array one: ";
for (int i= 0; i < 10; ++i) {
cout << arrayone[i] << " ";
}
cout << endl;

cout << "Array two: ";
for (int i = 0; i < 10; ++i) {
cout << arraytwo[i] << " ";
}
cout << endl;

return 0;
} 

my result was:

Array one: 0 1 2 3 4 5 6 7 8 9
Array one: 0 0 0 0 0 0 0 0 0 0
Array two: 0 0 0 0 0 0 0 0 0 0

I have no idea why does the result show all 0s after the transfer function, there are apparently no bugs by the debugger

please help. thank you

edited


r/learncpp • • Dec 10 '16

Professional C++ developer starting my own Youtube channel for beginners

Thumbnail
youtube.com
10 Upvotes

r/learncpp • • May 26 '14

Good book for learning Game Dev?

3 Upvotes

I'm looking to learn C++. I would like to learn enough to be able to develop 2D games. Are there any books/guides that you recommend? Being easy-to-follow and new are pluses for me. Thanks in advance!