c++ function input error [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm writing a monte carlo simulation and my 1st function is an input but it keeps kicking back an error stating that the variable "is not declared in this scope", I tried adding the variable type in the main and it still doesn't build. I then added the variable type in the function (cin>>rounds to cin>> int rounds), and the error changed but still doesn't work. Can anyone tell me what's going on and what I need to do get the function to work.
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
int getInput();
using namespace std;
int main (void){
//set up random
srand(time(NULL));
//1st function
getInput();
}
/* #description gets a valid user input
* #param output and input
*/
int getInput(){
cout<<"enter amount of rounds";
cin>> rounds; **(error is here on line 24 ("rounds not declared in
this scope")**
}

"is not declared in this scope"
This means that where you try to use your variable (i.e. rounds), it is not known. Declaring it inside main wouldn't help, since the scope of getInput != scope of main.
You have 4 possibilities:
Declare in main and send as an argument [will be in scope for main + getInput]
Declare inside getInput [will be in scope for getInput]
Declare as global (i.e. above main) [will be in scope for everyone]
Add extern and declare wherever you like [will be in scope for everyone]
Clarification: "will be in scope for..." means "from here on..."
Here are code snippets to show your options:
/* 1st option */
void foo(int x){
x = 1;
}
int main()
{
int x;
foo(x);
return 0;
}
/*************************************/
/* 2nd option */
void foo(){
int x;
x = 1;
}
int main()
{
foo();
return 0;
}
/*************************************/
/* 3rd option */
int x;
void foo(){
x = 1;
}
int main()
{
foo();
return 0;
}
/*************************************/
/* 4th option */
void foo(){
extern int x;
x = 1;
}
int main()
{
foo();
return 0;
}
int x;
In the I would change your code into something like this:
#include <iostream>
int getInput();
using namespace std;
int main (void){
...
int in = getInput();
...
}
/* #description gets a valid user input
* #param output and input
*/
int getInput(){
int rounds;
cout << "enter amount of rounds";
cin >> rounds;
return rounds; // dont forget to return :)
}

You will need to declare the variable (as int or long whatever desired) in the function as given below:
int getInput(){
int rounds;
cout<<"enter amount of rounds";
cin>> rounds; **(error is here on line 24 ("rounds not declared in
this scope")**
}

Related

Return Value cannot be seen on console [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
#include<iostream>
#include<string>
using namespace std;
int test(int i) {
int a = i-1;
return a;
}
int main()
{
test(3);
}
I am not getting returned value on console screen
Expected that the return value would be shown on console
A quick code review:
#include<iostream> // Not used
#include<string> // Not used
using namespace std; // Bad Practice
int test(int i) {
int a = i-1;
return a;
}
int main()
{
test(3); // Function called, returned value discarded.
// No code is ever called to print.
}
What you could do if you want to see the return value printed:
int main() {
std::cout << test(3) << '\n';
}
This revised main() function will print the value returned by your test() function to stdout. It will utilize <iostream> to do so.

Error converting a char[] string to uppercase [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This code is giving me an error that sptr was not declared in the while loop.
#include<iostream>
#include<ctype.h>
#include<stdlib.h>
using namespace std;
void convertToUppercase (char *s);
main()
{
{
char s [40]="Welcome to gbk gang";
cout<<"Before converting The string is! "<<s<<endl;
void *convertToUppercase(s) ;
cout<<"After converting The string is! "<<s<<endl;}
void convertToUppercase(char *sptr)
while(*sptr!='\0')
{
if(islower(*sptr))
}
return 0 ;
}
The code shown has multiple syntax mistakes.
Starting with a spurious { that causes the code from void convertToUppercase(char *sptr) onward to become part of main() rather than be in a separate function definition. void convertToUppercase(char *sptr) itself should not compile inside of main(), you should have gotten an error about that. But while(*sptr!='\0') would also fail to compile because there is no sptr variable declared in main().
You need to remove that spurious {. Then void convertToUppercase(char *sptr) would be the start of a new function definition properly.
But you still have 2 other mistakes.
void *convertToUppercase(s) ; does not call the convertToUppercase() function. It declares a void* variable named convertToUppercase that points at the 1st char of s[].
And if(islower(*sptr)) is incomplete.
The code should look more like this instead:
#include <iostream>
#include <cctype>
using namespace std;
void convertToUppercase (char *s);
int main()
{
char s[40] = "Welcome to gbk gang";
cout << "Before converting The string is! " << s << endl;
convertToUppercase(s);
cout << "After converting The string is! " << s << endl;
return 0;
}
void convertToUppercase(char *sptr)
{
while (*sptr != '\0')
{
unsigned char ch = static_cast<unsigned char>(*sptr);
if (islower(ch)) {
*sptr = static_cast<char>(toupper(ch));
}
++sptr;
}
}
Demo

printing global variable in local block

#include <iostream>
using namespace std;
int x=15;
int main()
{
int x=10;
{
int x = 5;
cout<<::x; // should print 10;
}
return 0;
}
Is there any way to print x=10 without changing variable names, variable values and position of cout?
I assume this is an academic question (puzzle) because nobody should write code like that. In the same spirit, here's a way to make it print 10 instead of 15 without changing variable names, variable values and the position of cout:
#include <iostream>
using namespace std;
int x=15;
int main()
{
int x=10;
{
int x = 5;
#define x x-5
cout<<::x; // should print 10;
}
return 0;
}
Normally you should parenthesize such expressions in macros, like (x-5). In this case, that would be counterproductive :)
No you can't
An inner block, because it is a different block, can re-utilize a name existing in an outer scope to refer to a different entity; in this case, the name will refer to a different entity only within the inner block, hiding the entity it names outside.
Further information here: http://www.cplusplus.com/doc/tutorial/namespaces/
You cannot access x=10 in the inner block where you defined x=5. It can only see x=5 as x=10 is hidden at that point.
Ref: 3.3.7/1
A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2).
If you don't mind some horrible undefined behaviour, we could make assumptions about where local variables are stored on the stack. This works on my machineā„¢ using g++ without any additional flags (although even -O1 breaks it):
#include <iostream>
using namespace std;
int x=15;
int main()
{
int x=10;
{
int x = 5;
cout<<*((&x) + 1); // should print 10;
}
return 0;
}
This is based on the assumption that local variables are placed on the call stack (or some other place) consecutively in main memory, in reverse order of declaration. It breaks in many cases, such as having a different order, having x=10 be placed in a register, or x=10 being optimized away entirely because it's unused.
#include <iostream>
using namespace std;
int x = 15;
int main()
{
int x = 10;
{
int x = 5;
}
cout << x; // should print 10;
return 0;
}
you should probably put cout<< to outside

How do I use a class constructor to get a value from a file? C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
sorry if this is obvious, I am new to classes.
I want the code to read the first value of a file from a class constructor (a getter), and right now the constructor returns a random number instead of the first number of the file, so it's clearly not reading the file for some reason. Thank you for your help, the code is in the following link.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
class bankAccount
{
public:
int getAcctNum();
bankAccount(string n);
bankAccount();
private:
ifstream sourceFile;
char tempWord;
int accountNumber;
double initialBalance;
double interestRate;
double serviceCharge;
double depositAmt;
double withdrawAmt;
double totalDeposits;
double totalWithdraws;
double tempAmt;
};
int main()
{
string fileName;
cout << "Enter the name of the data file: ";
cin >> fileName;
cout << endl;
bankAccount object(fileName);
cout << "Account number: " << object.getAcctNum() << endl;
return 0;
}
bankAccount::bankAccount(string n)
{
ifstream sourceFile(n.c_str());
}
bankAccount::getAcctNum()
{
sourceFile >> tempWord;
sourceFile >> accountNumber;
return accountNumber;
}
The value in the file that it should read is:
# 123456
Your problem has to do with scope. For a quick TL;DR how do I fix it, just scroll all the way to the bottom.
An easy way to think of scope is by thinking: where is my variable defined. A variable defined outside of main is said to have global scope, as it's a global variable. That means that no matter where you reference it (after it's definition) it will be defined (not necessary initialized, however). If a variable is defined within a function, it's scope is limited to that function. So it will be defined in that function only, not in other functions. If you define a variable within a for loop, or an if statement, or anywhere were you open a new scope using { }, that variable is scope-limited, ie it is only defined in that scope, and will stop being defined after the closing brace is read. Here is an example:
#include <iostream>
// rest of includes and usings and function prototypes, etc
const string AUTHOR_NAME = "ME"; // this is now defined everywhere in the program.
int main() {
bool program_busy = true; // this is only defined in main()
}
bool return_program_busy() {
cout << AUTHOR_NAME << endl; // this works as AUTHOR_NAME is defined
return program_busy; // this won't work, as program_busy is not defined in this scope.
}
void better_example(bool program_busy) {
int version = 0.1;
for(int i = 0; i < 10; i++) {
do_something(version, i); // this works as both are defined.
}
// i is no longer defined as we exited it's scope!!
if(program_busy) { // this opens a new scope.
int version = 0.2;
do_something(version, 0); // wait, is version 0.1 or 0.2???
}
}
As you can undoubtedly see in the last line, there are two versions (with different scopes) that are defined. So which one does it use? The one with the smaller scope, or the more local one. version 0.2 is only defined within the if(program_busy) scope, so it's smaller than the entire function scope, so it is used. Can you spot the error in your own code now?
ifstream sourceFile has two scopes: a global-class one, i.e. it is defined for the entire class, and a local scope for the constructor function you have.
ifstream sourceFile(n.c_str()); will create a new variable with a limited scope and initalize it, leaving the sourceFile with a more global scope uninitialized. The way to fix it is simply not redefine the sourceFile variable.
TL;DR: change ifstream sourceFile(n.c_str()); to sourceFile.open(n.c_str());

How main function call in C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have created function and call above the main() function. It is successfully call the function in GCC compiler on Linux platform. I don't understand, how main function call my own function.
#include <iostream>
using namespace std;
int myFunc();
int ret = myFunc();
int main()
{
cout << ret << endl;
}
int myFunc()
{
int i = 10, j = 20, k;
k = i+j;
return k;
}
Global variables are initialized before main is called. Therefore the call to myFunc happens before main is called. Your main function doesn't call myFunc at all.
It would have been very obvious if you used a debugger and set breakpoints in the myFunc and main functions, and looking at the call stack.
As Some programmer dude explained, it is being called before the main function.
To not be confused, I suggest that you explicitly call the myFunc() in the main function:
#include <iostream>
using namespace std;
int myFunc();
int main()
{
int ret = myFunc();
cout << ret << endl;
}
int myFunc()
{
int i = 10;
int j = 20;
return i+j;
}