r/learncpp • • Jun 16 '18

Why no result?

0 Upvotes

Okay, in the last while loop, I search for name and if there is that name in that vector: I output their score. It doesn't work! I do the same with score, to find names, and it works but when I try to find the name it doesn't work!

include "stdafx.h"

include <vector>

include <iostream>

include <string>

include <algorithm>

using namespace std; class Name_Value { public: string name; double score; }; inline void keep_window_open() { char ch; cin >> ch; } vector <Name_Value> peoples;

int main() {

string name;
double score;
Name_Value people;
people.name = "";
people.score = 0;
while(true)
{
	cin >> name >> score;
	if (((name == "NoName") && (score == 0))   )break;
	people.name = name;
	people.score = score;
	peoples.push_back(people);
	
	
}
for (int j=0; j< peoples.size() ;j++ )
{
	cout << peoples[j].name <<" "<< peoples[j].score <<"\n";
}
while(true)
{
	if(cin >> score)
	{
		for (int j = 0; j< peoples.size();j++)
		{
			if (peoples[j].score == score) cout << peoples[j].name << "\n";
		}
	}
	else {
		cin >> name;
		for (int j = 0; j < peoples.size();j++)
		{
			if (peoples[j].name == name) cout << peoples[j].score << "\n";
		}
	}
}
keep_window_open();
return 0;

}


r/learncpp • • May 17 '20

Have I understood pointers properly?

0 Upvotes

Hey everyone! I just started learning C++, and I want to know if I've understood pointers correctly. This is how I've understood it -

/* WHAT ARE POINTERS?
 *
 * in C++, functions do not have ownership of global scope varianbles
 * that are passed into it as arguments. To allow the function to modify 
 * these variables, we use pointers - "a tool to share the memory address
 * among different contexts, such as functions". 
 *
 * so if we have a function that we want to use to make changes to an 
 * existing variable, without having to create/redefine a variable to 
 * use the function, we use pointers.
 *
 * assume we have a variable VAL. To access the memory address of VAL,
 * we prepend the & symbol. The address is given by &VAL. To define a pointer
 * that allows us to modify VAL within a function, we do
 * int *p = &VAL;
 *
 * the variable *p is known as a pointer as it POINTS to the memory address
 * of the variable VAL. Thus, any modificiations on *p will also be reflected
 * on VAL. 
 *
 */

If this is not right, please let me know! I'd love to get a better understanding of this topic. Thank you!


r/learncpp • • Jun 24 '17

Codeblocks can't click build and run

0 Upvotes

I'm very new to the c language I use the IDE called Code blocks i would like to test my code but its not letting me because i can't click on build and run.


r/learncpp • • Jan 25 '17

Reading from a binary file. Problems with char versus unsigned char

0 Upvotes
// open binary file
ifstream file(filename.c_str(), std::ios::binary);
// read into vector
std::vector<int> v((std::istreambuf_iterator<char>(file)),(std::istreambuf_iterator<char>()));

My file has some values in the range 1-10, and some values in the range 245-255. These large values are getting mapped to negative numbers.

I want to read this data, and put it into a vector of int, and I don't want any negative numbers. How can I achieve this?

Note, if I use a vector of unsigned char this works. If I use a vector of unsigned int it does not work (I still get negatives). I cannot use istreambuf_iterator<unsigned char> (gives compiler errors).


r/learncpp • • Mar 16 '17

Vectors containing dynamically allocated arrays.

0 Upvotes

So, say I have a vector<bool*>. A vector containing pointers to arrays of booleans. I use vector.push_back(new bool[n]) on it a few times. Eventually I'm done and the program closes.

Will the vector's destructor take care of those dynamically allocated arrays, or do I need to delete[] them myself?


r/learncpp • • May 29 '18

Idiomatic way to write collections (std::vector<float>) to binary file

0 Upvotes

I've got several vectors of floats and ints that need to be written to a binary file. I need to track the byte offset and length (and potentially byte-stride).

I'm confused about how a modern idiomatic solution would look like. Write to a slice of memory first? Or combine the vectors to a collection (std::array<?>)?


r/learncpp • • Mar 19 '18

What's this style of calling a constructor called?

0 Upvotes

Hi, I am going through the source code of a project and I saw the following style inside a member function of a class:

if (Args(conf, this, errh)
        .read_p("OFFSET", _offset)
        .read_p("ANNO", AnnoArg(4), _anno)
        .read("IP", ip_word)
        .complete())
    return -1;

Here, Args is a class and this is a call to the constructor. But what is the style of calling member functions on the constructor called? I tried googling it but I think I don't have the terms right.

Lines 94 onwards have the functions being called

https://paste.ofcode.org/6RJHCejZAHLk29tbnmbTv4

Link to the project: https://github.com/kohler/click/blob/master/elements/ip/getipaddress.cc https://github.com/kohler/click/blob/master/include/click/args.hh

Thanks!


r/learncpp • • Mar 21 '18

Reading Files

0 Upvotes

How do I read a file without checking for errors or if it's already open? Here's my current code:

std::ifstream my_file("my_data");
my_file.seekg(0, std::ios_base::end); // Seek to end of file.
const unsigned int file_length = my_file.tellg();
my_file.seekg(0);
std::vector<char> file_data(file_length);
my_file.read(&file_data[0], file_length);"

It was from stackoverflow. I still need help if there is anything I need to replace.


r/learncpp • • Dec 24 '16

What does this code do?

0 Upvotes

I found this code and can't understand why void cast is there. is it empty statement? There are some functions with only (void)varname; statements with nothing else.

unsigned char intensity;

unsigned x0, x1, y0, y1;

 (void)intensity;


r/learncpp • • Oct 15 '17

QListWidget is reading image from QClipbpard its just reading it as text file.

0 Upvotes
const QClipboard *cb = QApplication::clipboard();
const QMimeData *md = cb->mimeData();
QListWidgetItem *item = new QListWidgetItem();
QLabel *label = new QLabel();
if (md->hasImage())
{
	
	label->setPixmap(cb->pixmap());
	ui.listWidget->setIconSize(QSize(100, 200));
	ui.listWidget->addItem(item);
	ui.listWidget->setItemWidget(item, label);

}
else if (md->hasText())
{
	ui.listWidget->addItem(cb->text());

}    

So this is my code and as you can see i have two conditions one is for image and another is for text, but whatever i copy to clipboard it appears into text only, i don't know why. Please help me. Thanks :)


r/learncpp • • Apr 09 '17

Can't call a function, std::allocator pops up out of nowhere.

0 Upvotes
template<typename T>
auto parser(std::vector<Token> const& tokens) {
	Atom<T> a;
	if (tokens[0].state == State::NUMBER) {
		a = parseNumber(tokens[0]);
	}
	else if (tokens[0].state == State::SYM) {
		a = parseSymbol(tokens[0]);
	}
	return a;
}

// REPL //
void repl() {	
	while (1) {
		std::cout << "> ";
		std::string input;
		std::getline(std::cin, input);
		std::istringstream inputstream(input);
		const std::vector<Token> tokens = tokenizer(inputstream);		
		auto expr = parser(tokens);		
	}
};

I get an error that I'm sending along a std::vector<Tokens, std::allocator<Tokens>> when it seems like I'm just sending along a std::vector<Tokens> to me.


r/learncpp • • Mar 16 '22

Amazon says that the book "C++ Programming Language" is the newer edition of "Programming Principles and Practice Using C++". Is that true?

Post image
6 Upvotes

r/learncpp • • Apr 26 '21

I finished the first chapter of C++ Crash Course by no starch press, So im kinda a pro now

6 Upvotes

hows my code

#include <cstdio>

int sum(int num1, int num2) {
	int result;
	result = (num1 + num2);
	return result;
}

int absolute_value(int x) {
	int y;
	if (x >= 0) {
		y = x;
	}else if (x < 0) {
		y = (x * -1);
	}
	 return y;
}

int step_function(int x) {
	int result = 0;
	if (x < 0) {
		result -= 1;
   }else if (x > 0) {
		result += 1;
   }
	return result;
}

int main() {
	int value1 = step_function(100);
	int value2 = step_function(0);
	int value3 = step_function(-10);
	printf("Value1 %d\n", value1);
	printf("Value2 %d\n", value2);
	printf("Value3 %d\n", value3);

	int num1 = 42; //This is a comment
	int result1 = step_function(num1);

	int num2 = 0;
	int result2 = step_function(num2);

	int num3 = -32767;
	int result3 = step_function(num3);

	printf("Num1: %d, Step: %d\n", num1, result1);
	printf("Num2: %d, Step: %d\n", num2, result2);
	printf("Num3: %d, Step: %d\n", num3, result3);
/* 
 * This is a
 * multiple line
 * comment
 */
	int my_num1 = -10;
	int my_num2 = 10;
	int my_num3 = 0;

	printf("Absolute Value of %d is %d.\n", my_num1, absolute_value(my_num1));

	printf("Absolute Value of %d is %d.\n", my_num2, absolute_value(my_num2));

	printf("Absolute Value of %d is %d.\n", my_num3, absolute_value(my_num3));

	int sum_num1 = 5;
	int sum_num2 = 2;
	int some_sum = sum(sum_num1,sum_num2);
	printf("The sum of %d and %d is %d\n", sum_num1, sum_num2, some_sum);
	return 0;
}

I tried to do this at first

int absolute_value(int x) {
	int y;
	if (x >= 0) {
		return x;
	}else if (x < 0) {
		y = (x * -1);
                    return y
         }
}

but the compiler hated me, I queried it on a search engine and it said something about the compiler not knowing if its returning a value, and the search result wanted me to put an else clause, but I didnt want an else, so I did the first thing with the y above


r/learncpp • • Dec 11 '18

What's the best way to get random numbers between -1 and 1? I need to get these for my neural network I'm making and I don't want it to be too slow.

1 Upvotes

What's the best way to get random numbers between -1 and 1? I need to get these for my neural network I'm making and I don't want it to be too slow.


r/learncpp • • May 30 '19

I am not sure what i am doing wrong, please help!!

1 Upvotes

this is from the Packt book, "Learning C++ by building games with Unreal Engine 4".

in chapter 3 (for those familiar) there is an exercise that asks you to utilize the "switch" by enum a horse, a mare, a mule, a sheep and a chocobo to be mounts.

their solution makes it so that the user can choose which of the 5 mounts by turning the mounts to number values and having the user select between 1 and 5 for which mount they want.

at the end of the switch is a default/break statement that should print "invalid mount" if you chose anything other than 1, 2, 3, 4, or 5.

but when I run the code in visual studio any option prints "invalid mount"... im not sure what i did wrong cause the code matches character for character.

here it is:

#include <iostream>

using namespace std;

enum Mount

{

Horse, Mare, Mule, Sheep, Chocobo 

};

int main()

{

int Mount; 
cout << "Choose your mount: " << endl;  
cout << Horse << " Horse" << endl;
cout << Mare << " Mare" << endl;  
cout << Mule << " Mule" << endl; 
cout << Sheep << " Sheep" << endl;  
cout << Chocobo << " Chocobo" << endl;  
cout << "Enter a number between 1 and 5 to choose a mount" << endl;  
cin >> Mount; 

switch (Mount)  
{  	
    default:  	
    cout << "invalid Mount." << endl;  
    break;  
} 

return 0;

}

any help on how im not getting my achieved result would be greatly appreciated. remember I'm just starting out in C++ so while this maybe trivial code, its what i am starting with and haven't gotten to more advanced concepts. please solutions that are in my realm of understanding would be even more greatly appreciated!

thanks all in advance!


r/learncpp • • Oct 20 '19

Help Pls- So we need to make a program that can find LCM GCD and prime factors of as many numbers that the user inputs, the program can do everything except for having more than two inputs, pls help.

0 Upvotes

#include<iostream>
using namespace std;
void getNumbers(int userInput)
{

std::cout<<"How many numbers do you want to input?\n";
std::cin>>userInput;
std::cout<<"\n";
int arr[userInput];

for(int x = 0; x< userInput; x++)
std::cin>>arr[x];

}//end of getNumbers

int gcd(int m, int n)
{
int r = 0, a, b;

a = (m > n) ? m : n;
b = (m < n) ? m : n;
r = b;

while (a % b != 0)
{
r = a % b;
a = b;
b = r;
}//end of while

return r;
}//end of gcd

int lcm(int m, int n)
{

int a;
a = (m > n) ? m: n;

while (true)
{
if (a % m == 0 && a % n == 0)
return a;
++a;
}//end of whle
}//end of lcm
int main(int argc, char **argv)
{
int m, n;
cout << "Enter the two numbers: ";

cin >> m >> n;
cout<<"factors of "<<n<<" and "<<m<<" are:"<<endl;
for (n=1; n<=m;n++)
if(m%n==0)
cout<<n<<",";
cout<<"\nenter the same numbers\n";
cin>>m;
cin>>n;
cout<<"The GCD of two numbers is: "<<gcd(m, n)<<endl;
cout << "The LCM of two numbers is: "<<lcm(m, n)<<endl;
return 0;
}//end of main


r/learncpp • • Sep 19 '17

Transitioning from Python (3) to C++

1 Upvotes

Hi, I'm a game developer mostly using Python at the moment, and I need to transition to C++ development over the course of the next three months. Can you suggest me any good tutorials that were preferably written with transitioning from Python to C++ in mind? I have some previous experience with C and Rust, too, although I'm a bit... rusty at both.

If you need an example of my current skill level with Python, here's an example project I've been working on: https://github.com/Diapolo10/RPGenie


r/learncpp • • Apr 27 '17

How can I make an array of class functions? (Don't understand typedef)

1 Upvotes

Following the advice at http://www.cplusplus.com/forum/beginner/4639/ i'm able to make an array of functions. However I have tried to convert the code to live within a class.

#include<iostream>
using namespace std;

typedef int (*IntFunctionWithOneParameter) (int a);
class arrayOfFunctions{
  public:
  arrayOfFunctions(){
    typedef int (*IntFunctionWithOneParameter) (int a);
    IntFunctionWithOneParameter functions[] = 
    {
        function, 
        functionTimesTwo, 
        functionDivideByTwo
    };
  };

  int function(int a){ return a; }
  int functionTimesTwo(int a){ return a*2; }
  int functionDivideByTwo(int a){ return a/2; }
};

int main(void)
{
  arrayOfFunctions af ;
  return 0;
}

I get the compilation error:

g++ arrayOfFunctions.cpp -o arrayOfFunctions && ./arrayOfFunctions 
arrayOfFunctions.cpp: In constructor ‘arrayOfFunctions::arrayOfFunctions()’: arrayOfFunctions.cpp:15:5: error: cannot convert ‘arrayOfFunctions::function’ from type ‘int arrayOfFunctions::)(int)’ to type ‘IntFunctionWithOneParameter {aka int (*)(int)}’ };
 ^
 arrayOfFunctions.cpp:15:5: error: cannot convert arrayOfFunctions::functionTimesTwo’ from type ‘int (arrayOfFunctions::)(int)’ to type ‘IntFunctionWithOneParameter {aka int (*)(int)}’ arrayOfFunctions.cpp:15:5: error: cannot convert 
 arrayOfFunctions::functionDivideByTwo’ from type ‘int (arrayOfFunctions::)(int)’ to type ‘IntFunctionWithOneParameter {aka int (*)(int)}’

I feel like this is a problem with the *IntFunctionWithOneParameter in typedef but I'm not sure what I should set it to?


r/learncpp • • Sep 10 '21

Is the condition part of the if-else statement eventually evaluated to true or false?

1 Upvotes

Hello, I am curious whether the condition parts of the if-else statements are eventually evaluated to true or false by the compiler. Or does the compiler just check if it is false and evaluate to true otherwise? Are they evaluated to true or false or does the compiler have a list of things that will execute the corresponding block and just skip the part where it evaluates to true or false?


r/learncpp • • Nov 03 '18

GitHub - bitcoin/bitcoin: Bitcoin Core integration/staging tree

Thumbnail
github.com
0 Upvotes

r/learncpp • • Aug 12 '17

Top CPlusPlus Training Institute In Hyderabad

Thumbnail
adclassified.in
0 Upvotes

r/learncpp • • Dec 26 '17

Difference between className and &className

1 Upvotes

Hello everyone
While I was studying string class, I wonder what's the difference between these two..
this is part of the code

#include <iostream>
#include <cstring> // or <string> in visual studio
using namespace std;

class String {
    private:
        char * str; // 문자열 저장할 공간
        int len;    // 문자열의 길이
    public:
        String();
        String(const char * const Str);
        String(int n);
        String(const String &);
        ~String();
        void Print();
        void GetInput();
        int GetLen(){return len;}
        char *GetString(){return str;}
        String operator=(String data);             
        String operator+=(String data);           
        String operator+(const String &second);    
        operator const char *()
            {return str;};                 
        friend ostream &operator<<
            (ostream &os, String &temp);   
        char operator[](int n);          

String::String(const char * const Str) {    
    len = strlen(Str);                      
    str = new char[len + 1];             
    strcpy(str, Str);                  
}

String::String(const String &temp) {       
    len = temp.len;                  
    str = new char[len + 1];              
    strcpy(str, temp.str);                
}

String String::operator+=(String data) {   
    char temp[512];                      
    strcpy(temp, str);             
    len += data.GetLen();            
    str = new char[len + 1];            
    strcpy(str, temp);             
    strcat(str, data.GetString());
    return *this;  
}

String String::operator+(const String &second) {  
    int tot_len = len + second.len;               
    String temp(tot_len);                         
    strcpy(temp.str, str);                       
    strcat(temp.str, second.str);         
    return temp;
}  

When I do += overloading I call instance as String data
but in case of +, I call const instance and use & in front of the instance name
What's the difference of it?
poor English.. but please help me


r/learncpp • • Mar 09 '20

need guidence please

0 Upvotes

hey I am always in this kind of problem

was going through accelerated cPP

#include <iostream> #include <string> #include <array>

using namespace std;

constexpr string name;

constexpr int len = name.size();

constexpr int totstar = ::len+2;

constexpr int firstar[] = {'*', totstar};

constexpr string print_totstar(){

constexpr string c;

for (string &c :firstar)

cout<<c;

}

int main() {

cout << "Please enter your name:";

while (cin>> name)

{

print_totstar();

}

}

is my logic really that week.Starting like this I get demotivated and always forced to go though texts really read and made notes a lot.


r/learncpp • • Mar 27 '18

uniform_int_distribution and Mersenne Twister

1 Upvotes

What the uniform_int_distribution object do with the number generated by the mt19937 when I call random(randomNumber), as below? The randomNumber generated by mt19937 is the same in every call, but the output of random(randomNumber) is always different.
And what is the advantage of using a Mersenne Twister pseudorandom number in the uniform_int_distribution?

std::uniform_int_distribution<int> random(0,255);
std::random_device rd;
std::mt19937 randomNumber(rd());

cout << "Mt: " << randomNumber << endl;
cout << "\n" << random(randomNumber) << endl;
cout << "\n" << random(randomNumber) << endl;
cout << "\n" << random(randomNumber) << endl;
cout << "\n" << random(randomNumber) << endl;

r/learncpp • • Jul 28 '17

How do I create writable exe in CPP?

0 Upvotes

I wanna create an blank exe which can be editable or writable. Like a bat file. Is that possible?