Got some problems with functions and how they interfere with main - c++

I recently tried making a program that has several functions outside of main, but for some reason the "declaration is incompatible with" all of my variables and functions. Is there an easy way of using functions outside of main and refer to the variables interchangably? The error i receive is:E0147. and this is my code:
#include <iostream>
using namespace std;
int dager;
int mintemp;
int maxtemp;
int nedbor;
int i = 1;
int j;
int mintempg;
int maxtempg;
int nedborg;
int mintemp() {
cout << "hva er dag:" << i << " sin min temp? \n";
cin >> mintempg;
if (mintempg >= -70 && mintempg <= 70)
{
mintemp += mintempg;
}
else
{
cout << "ugyldig temperatur.";
mintemp();
}
}
int maxtemp() {
cout << "hva er dag:" << i << " sin max temp? \n";
cin >> maxtempg;
if (maxtempg >= mintempg && maxtemp <= 70)
{
maxtemp += maxtempg;
}
else
{
cout << "ugyldig temperatur.";
maxtemp();
}
}
int nedbor() {
cout << "hva er dag:" << i << " sin mm nedbør? \n";
cin >> nedborg;
if (nedborg >= 0 && nedborg <= 200)
{
nedbor += nedborg;
}
else
{
cout << "ugyldig mengde nedbor.";
nedbor();
}
}
int main() {
cout << "Hvor mange dager er det i måneden? " << "\n";
cin >> dager;
for (j = dager; j > 0; j--) {
if (dager >= 28 && dager <= 31)
{
mintemp();
maxtemp();
nedbor();
i++;
}
}
system("pause");
}
So as you can see it provides a lot of readability to my code to do it like this, which is why i decided i didn't want all of it to be in main. Also it makes it easier to reuse the code later.
Side question: Is there a way I can make the compilator not close whenever it has run through code without using system("pause"); ?, I seem to recall our professor mentioning it in one of our lectures, but I didn't quite catch it. Anyways all help appreciated !!

For your side question; In order to prevent the window from closing look at this post.
-If you are using Visual Studio and you are starting the console application out of the IDE: pressing CTRL-F5 (start without debugging) will start the application and keep the console window open until you press any key.
-You could insert std::getchar(); at the end of your main function. The function is included by .
reference: stackoverflow.com/questions/2529617/...

Related

CPP Guessing Game not working, its stops after i enter the name

I'm trying to make this kina guess game on C++, I'm a beginner and still learning.
What I'm trying to achieve is a guessing game of two const names, is very simple without errors but it's not working after I enter something. it should report until I find the correct name. Please also I don't want to change the structure of the code, just find why isn't working.
#include <iostream>
#include <string>
using namespace std;
struct Vlerat {
string guess01 = "Resul";
string guess02 = "Rejan";
int numruesi = 0;
};
int main() {
Vlerat funksioni;
string nameGuess;
int nameOkay = 0;
cout << "Gjej njerin prej dy emrava te fshehura." << endl;
cout << "Ndihm: Fillojn me Shkronjen 'R', dhe pas asaj vjen edhe nje shkronj 'e'" << endl;
do {
cout << "Shkruaj Emrin > "; cin >> nameGuess;
if (nameGuess == funksioni.guess01){
cout << "Ju e keni gjetur emrin e njerit nga personat duke provuar gjithesej:";
cout << funksioni.numruesi++ << " here." << endl;
nameOkay++;
}
if (nameGuess == funksioni.guess02) {
cout << "Ju e keni gjetur emrin e njerit nga personat duke provuar gjithesej:";
cout << funksioni.numruesi++ << " here." << endl;
nameOkay++;
}
funksioni.numruesi++;
} while(nameOkay = 0);
}
You should change while(nameOkay = 0); to while(nameOkay == 0);.
Because = is an assignment, but == is operator of comparing (equality)
Read about it here
And here

C++ Guessing Game Error

I do not know how to declare "random" in the parentheses for "int main()," and need help. (I am a beginner in C++)
Please take a look at my code, try it out, and please notify me with an answer when you think you know how to solve this problem. It'd mean a lot to me. Thanks! Meanwhile, I will keep trying to solve the problem myself as well.
Note: I am using Code::Blocks if you want to be specific.
The error is on Line 7/9 of my code.
Here is my updated code below:
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
int rn = random() % 21; // generates a random int from 0 to 20
// First output asking the user to guess the number
cout << "Please guess my number :" << endl;
int u;
cin >> u;
while (u != rn) // Calculates the answer that you give
{
// If the user's number is greater than the random number
// the program will let you know it's too large
if (u > rn)
{
cout << "You guessed too big!" << endl;
}
// On the other hand, if the user guesses to small
// the program will tell them that it's too small
else if (u < rn)
{
cout << "You guessed too small!" << endl;
}
// If the user does not get the right number, the program
// will tell the user to guess again
cout << "Please guess again :" << endl;
cin >> u;
}
// If the user guesses the number correctly, the program
// will say that they got it right, and end the program
cout << "You guessed it right!" << endl;
getch();
}
Here's the updated compiler error:
||=== Build: Debug in Guess The Number (compiler: GNU GCC Compiler) ===|
C:\Users\Minecraftship\Documents\CPP Programs From Book\Guess The Number\main.cpp||In function 'int main()':|
C:\Users\Minecraftship\Documents\CPP Programs From Book\Guess The Number\main.cpp|12|
error: 'randomize' was not declared in this scope|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
Remove the semicolon near main, the compiler is telling you exactly what the issue is:
int main ();
Should be
int main ()
Your code will also not compile even after fixing this because you have not declared the std namespace. You can put this line at the top for now using namespace std; but it is bad practice. You should declare it manually using the scope resolution operator.
And a number of other issues as already mentioned in the comments above, make sure to read the compiler output thoroughly because it tells you what line is causing the issue.
Your code should look like:
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
int rn = random() % 21; // generates a random int from 0 to 20
// First output asking the user to guess the number
cout << "Please guess my number :" << endl;
int u;
cin >> u;
while (u != rn) // Calculates the answer that you give
{
// If the user's number is greater than the random number
// the program will let you know it's too large
if (u > rn)
{
cout << "You guessed too big!" << endl;
}
// On the other hand, if the user guesses to small
// the program will tell them that it's too small
else if (u < rn)
{
cout << "You guessed too small!" << endl;
}
// If the user does not get the right number, the program
// will tell the user to guess again
cout << "Please guess again :" << endl;
cin >> u;
}
// If the user guesses the number correctly, the program
// will say that they got it right, and end the program
cout << "You guessed it right!" << endl;
getch();
}
Someone else got to it. There are no semicolons after signatures to methods like main().
One other thing not mentioned, I'm guessing you want
while (u != rn)
Also, be careful of the difference in "=" and "==".
BTW -- Welcome to C++!!!
a little more portable version (doesn't use conio.h) which lets the computer play against himself:
#include <iostream>
#include <cstdlib>
#include <ctime>
int get_random_in_range(int min, int max)
{
return std::rand() % (max - min) + min;
}
// returns 0 if user guessed right, negative value if user
// guessed too small, positive if user guessed too big
int check_user_guess(int guess, int my_secret)
{
return guess - my_secret;
}
int main ()
{
int my_guess = get_random_in_range(1, 10);
std::cout << "I think of " << my_guess << std::endl;
std::cout << "Please guess my number: ";
int user_guess = get_random_in_range(1, 10);
std::cout << user_guess << std::endl;
while (check_user_guess(user_guess, my_guess) != 0)
{
std::cout << "You guessed " << user_guess << std::endl;
if (check_user_guess(user_guess, my_guess) > 0)
{
std::cout << "You guessed too big!" << std::endl;
}
else if (check_user_guess(user_guess, my_guess) < 0)
{
std::cout << "You guessed too small!" << std::endl;
}
std::cout << "Please guess again: ";
user_guess = get_random_in_range(1, 10);
std::cout << user_guess << std::endl;
}
std::cout << std::endl << "You guessed it right!";
}
try it here: http://coliru.stacked-crooked.com/a/5bf0b9201ef57529

Reading into an Array Multiple Times

I'm having a little trouble with my code. It's pretty much supposed to open two files, and compare the first twenty line of the file "StudentAnswers.txt" [inputted as a char into a char array] against a char value in (each line of another file) "CorrectAnswers.txt" in another array at the same position (index). It's like a linear search, but the same position in the arrays. Then a report should be displayed, detailing which question the student missed, the given answer, the correct answer, and if the student passed (got >= 70%) or not, like the following:
Report for Student X:
2 (A/D), 3 (C/D), 5(D/A)
This student passed the exam!
Then it should clear the SAArray, and feed the next twenty lines from StudentAnswers.txt, and start the process all over again. I guess the program has to determine the number of students from (lines of 'StudentAnswers.txt' file / 20).
I'm having trouble displaying the report, and having the array clear itself after the program. I'm guessing this can be done with a while loop and an accumulator for the number of students (to be determined by above equation).
Also, Visual Studio seems to go to "Missed __ questions for a total of ___ %", and then keep looping -858993460.
Any help would be appreciated.
#include <iostream>
#include <fstream>
#include <string>
#include <array>
#include <algorithm>
using namespace std;
void GradeReturn(char[], char[], int, int, int);
string PassFail(float);
int main()
{
ifstream SA("StudentAnswers.txt");
ifstream CA("CorrectAnswers.txt");char CAArray[20];
char SAArray[20];
// char SA2Array[20];
bool isCorrect;
int correct;
int incorrect;
int counter;
correct = 0;incorrect = 0;
counter = 0;
cout << endl;
if (!SA.fail())
{
cout << "'StudentAnswers.txt' file opened successfully." << endl;
cout << "'CorrectAnswers.txt' file opened successfully." << endl << endl;
int a = 0;
int b = 0;
while (a < 20)
{
CA >> CAArray[a];
a++;
} // while loop to feed char into the array
while (b < 20)
{
SA >> SAArray[b];
b++;
}
} // while loop to feed char into array
CA.close(); // closing "CorrectAnswers.txt"
SA.close(); // closing "StudentAnswers.txt"
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter);
return 0;
}
void GradeReturn(char CAArray[], char SAArray[], int correct, int incorrect, int counter)
{
float percent;
float hundred;
int student;
int catcher[20];
int writeCatcher; int starter;
int catcher_size;
student = 0;
writeCatcher = 0;
catcher_size = ((sizeof catcher) / 4);
while (counter < 20)
{
if ((CAArray[counter]) == (SAArray[counter]))
{
correct++;
cout << "Good job!" << endl;
} // correct handling
else
{
incorrect++;
cout << "You got question " << counter << " wrong." << endl;
counter >> catcher[writeCatcher];
writeCatcher++;
} // incorrect handling
counter++;
} // while loop to determine if a student got a question right or wrong
static_cast <float> (incorrect); // float conversion
cout << endl; // for cleanliness
percent = ((static_cast <float> (correct)) / 20); // percentage
hundred = percent * 100;
PassFail(percent);
if (PassFail(percent) == "pass")
{
student++;
cout << "Report for Student " << student << ":" << endl;
cout << "-----------------------------" << endl;
cout << "Missed " << incorrect << " questions out of 20 for ";
cout << hundred << " % correct." << endl << endl;
starter = 0;
while (starter < (sizeof catcher)
{
if(1=1)
{
catcher_size
}
else
{
cout << "";
starter++;
}
}
}
else if (PassFail(percent) == "fail")
{
student++;
cout << "Missed " << incorrect << " questions out of 20 for ";
cout << hundred << " % correct." << endl << endl;
while (starter < catcher_size)
{
if ((catcher[starter]) == -858993460)
{
starter++;
}
else
{
cout << "";
starter++;
}
}
}
return;
}
string PassFail(float percent)
{
if (percent >= 0.70) // if <pass>
{
return "pass";
}
else // if <fail>
{
return "fail";
}
cout << endl;
}
To get a loop you should keep streams open instead of closing them after reading 20 lines.
As pseudo code that would be:
a = 0;
while(streams_not_empty)
{
CA >> CAArray[a];
SA >> SAArray[a];
++a;
if (a == 20)
{
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter);
a = 0; // Reset a
}
}
CA.close(); // closing "CorrectAnswers.txt"
SA.close(); // closing "StudentAnswers.txt"
You would also need to pass correct, incorrect, counter by reference so that the GradeReturn can change their value and their by do the accumulation.
Like:
void GradeReturn(char CAArray[], char SAArray[], int& correct, int& incorrect, int& counter)
Further you shouldn't rely on being able to read exactly Nx20 lines from the files every time. A file could have, e.g. 108 (5x20 + 8) lines, so you code should be able to handle the with only 8 lines. In other words, don't hard code 20 in your function like while (counter < 20). Instead pass the number of lines to be handled and do while (counter < number_to_handle).
Something like this as pseudo code:
a = 0;
while(streams_not_empty)
{
CA >> CAArray[a];
SA >> SAArray[a];
++a;
if (a == 20)
{
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter, a);
// ^
a = 0; // Reset a
}
}
if (a != 0)
{
// Process the rest
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter, a);
}
CA.close(); // closing "CorrectAnswers.txt"
SA.close(); // closing "StudentAnswers.txt"
One problem you have is you're trying to compare C-style strings with the == operator. This will compare them essentially as if they were pointers to char, i.e. compare whether they point at the same location in memory, not compare the contents of the string. I urge you to look up array-decay and c-string variables to understand more.
Specifically, if (PassFail(percent) == "pass") isn't going to do what you want it to. strcomp doc, strncmp doc using std::string variables instead of c-style strings would all work, but it would be better simply to compare percent to a value, i.e. if(percent >= 0.70 directly instead of calling PassFail and comparing a string.
There are many other issues here also, you at one point call PassFail but do nothing with the return value. The only side affect of PassFail is cout << endl, if that's what you intend, it's a poor decision and hard to read way to put a newline on the console.
Try asking your compiler for more warnings, that's often helpful in finding these types of issues. -Wall -Wextra work for gcc, you may have to read your compiler manual...

C++ - How to count how many times occur the same string in a list

I searched a lot on google and stackoverflow but I couldn't find my answer. I'm actually reading a C++ book (C++ Primer 5th Edition) and they're asking me to do an exercise.
"Write a program that reads several transactions and counts how many transactions occur for each ISBN" (Console Project)
This is my code atm :
Sales_item currentItem, item;
if (cin >> currentItem)
{
int cnt = 1;
while (cin >> item)
{
if (currentItem.isbn() == item.isbn())
{
++cnt;
}
else
{
cout << currentItem.isbn() << " occurs " << cnt << " times " << endl;
cnt = 1;
currentItem = item;
}
}
cout << item.isbn() << " occurs " << cnt << " times " << endl;
}
I won't explain how work the transactions so I'm gonna ask it in another way.
I type in my console 6(or more) random strings as exemple:
101A
102A
101A
101A
103A
102A
I want the result the result (output) to be:
101A occurs 3 times.
102A occurs 2 times.
103A occurs 1 times.
How would you do that?
Using std::map instead of list will be easier.
int main()
{
map<string,int> stringMap;
for (int i=0;i<3;i++)
{
cout<<"Enter string: ";
string s;
cin>>s;
if(stringMap.find(s)!=stringMap.end())
{
stringMap[s]++;
}
else
{
stringMap[s]=1;
}
}
for (map<string,int>::const_iterator itr = stringMap.cbegin(); itr!=stringMap.cend(); ++itr)
{
if(itr->second > 1)
cout<<itr->first << " occurs "<<itr->second<<" times"<<endl;
else
cout<<itr->first << " occurs "<<itr->second<<" time"<<endl;
}
return 0;
}
There are multiple approaches to a question like this, so the best would depend on your constraints. My approach would be:
while(GetInputString(str)) {
myStruct* ptr = existingList.Find(str);
if (!ptr) {
existingList.Add(str);
} else {
ptr->IncrementCount();
}
}
I've tried not to solve your problem for you - hopefully the answer gives you a template to work with...
#include <iostream>
#include <vector>
#include "Sales_item.h"
using namespace std;
void book_transactions(string isbn, int count);
int main()
{
vector<Sales_item> book_vec;
Sales_item book;
int total_transactions = 1;
// Reads in Sales_item objects
while (cin >> book)
{
book_vec.push_back(book);
}
// Compares ISBNs in vector, if two isbns are equal total transactions increases
for (int i = 0; i < book_vec.size() - 1; i++)
{
if (book_vec[i].isbn() == book_vec[i+1].isbn())
{
total_transactions = book_vec[i].get_units_sold() + book_vec[i+1].get_units_sold();
book_transactions(book_vec[i].isbn(), total_transactions);
}
}
}
void book_transactions(string isbn, int count)
{
cout << "ISBN: " << isbn << " " << "Transactions: " << count << endl;
}
I went into the Sales_item.h class and added a method to get the number of units sold. There was already a class member (unsigned return type) under private. I just created a getter and then created a vector of Sales_items. This solution seems to work. I'm sure the intended problem is not for an N set of sales_items, however this should work as a "duct-tape" solution. There is no need to play around with pointers at this point. A simple vector array and an algorithm to compare adjacent objects works just fine.

c++ while loop do max 1 time

class knygos {
public:
int nr;
char pavadinimas[25];
char autorius[25];
int egz_sk;
void go_to(int x, int y) {
COORD c;
c.X = x - 1;
c.Y = y - 1;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
void knygu_sarasas() {
ifstream myFile("data.bin", ios::in | ios::binary);
while (myFile.read ((char *) this, sizeof (knygos))) {
go_to(2,6);
cout << nr << endl;
cout << "Pavadinimas" << pavadinimas << endl;
cout << "Autorius" << autorius << endl;
cout << "Egzemploriai "<< egz_sk << endl;
}
myFile.close();
}
};
void main() {
knygos ob;
ob.knygu_sarasas();
}
Why when I use function go_to(2,6); while loop work only 1 time, when i not use this function loop work normaly (6 times) I not know where is problem, plese help guys ;)
Do you realize that if you set the cursor IN the loop to the (2, 6) position, all interation will wite to the SAME place, effetivly overwriting each other, and only producing "one" output for all 6 or many cicles?
You can using ncurses library for type of input such as keyboard/mouse and and output such as screen.If you use mvprintw() family functions,You can set X and Y same as gotoxy in DOS.
I forgot cout and cin and use ncurses library, you can learn it from here.