error: variable was not declared in this scope c++ - c++

I want to write the programm, that takes two numbers m and n as input and gives n-th digit of m number. Example m=1358 n=2 Output: 5
#include <iostream>
#include <string>
using namespace std;
int main(){
while(true){
int m = 0,n = 10;
char check;
while(true){
cout << "Enter please number m and which digit you want to select";
cin >> m >> n;
string m_new = to_string(m);
if(m_new.length() > n)
break;
else
cout << "n must be less than or equal to m";
}
cout << "The position" << n << "Of integer" << m << "is:" << m_new.substr(n,1);
cout << "Do you want to try again?(y/n)\n";
cin >> check;
while(check != 'y'&& check != 'n'){
cout <<"Please enter y or n\n";
cin >> check;
}
if(check == 'n'){
break;
}
}
return 0;
}
But i got an error: 'm_new' was not declared in this scope. Why do I get this error and how to fix it?

The m_new variable is local to nested while loop and can't be used outside of its scope. Scope represented by braces {} determines visibility:
int main() {
// can't be used here
while (true) {
// can't be used here
while (true) {
string m_new = to_string(m);
// can only be used here
}
// can't be used here
while (check != 'y'&& check != 'n') {
// can't be used here
}
// can't be used here
}
// can't be used here
}
Rethink the design to use only one while loop:
int main(){
char check = 'y';
while (std::cin && choice == 'y') {
int m = 0, n = 10;
std::cout << "Enter please number m and which digit you want to select";
std::cin >> m >> n;
string m_new = to_string(m);
// the rest of your code
std::cout << "Please enter y or n\n";
std::cin >> check;
}
}
Now the m_new variable is visible to everything inside the while loop.

m_new is declared inside the while loop. Anything declared inside a {...} block will only exist inside that block. The final use of it:
cout << "The position" << n << "Of integer" << m << "is:" << m_new.substr(n,1);
is outside the block, and therefore the variable no longer exists.

The variable "m_new" was just in the "while(true)" scope, and when your're asking this variable out of loop, it throws a compile-time error.
while(true){
...
string m_new = to_string(m);
...
}
...
cout << "The position" << n << "Of integer" << m << "is:" << m_new.substr(n,1);
^
...

Related

How to print product of all inputted numbers using a loop?

int main() {
cout << "Enter some numbers fam! " << endl;
cout << "If you wanna quit, just press q" << endl;
int n{ 0 };
int product = 1;
char quit = 'q';
while (n != 'q') {
cin >> n;
product = product* n;
cout <<"The product is : " << product << endl;
}
cout << endl;
cout << product;
return 0;
}
Whenever I print it out and cut the code using 'q', it prints me an infinite amount of "The product is 0". Also, how can I print out the final product of all numbers at the end?
So, there are some problems in your code.
First, you are taking input and assigning it to an int, which might not have been a problem, but you are also comparing the int to a char(which will cause problems in your case)
int n{ 0 };
while(n != 'q') {
cin >> n;
}
To solve that, you can make the n a string and then convert it into an integer with stoi(n) to use with the calculation
string n; // don't need to initialize a string, they are initialized by default.
int product = 1;
cin >> n; // Taking input before comparing the results
while(n != "q") { // Had to make q a string to be able to compare with n
product *= stoi(n); // Short for product = product * stoi(n)
cout <<"The product is : " << product << endl;
cin >> n; // Taking input for the next loop round
}
cout << endl;
cout << product;

C++ total keeps going up

Hello this is my first program with a do-while loop and its taken me a little while to get it down. I need to have the user enter 2 numbers, and raise the first number to the second number. I have finally got the coding to ask if "they would like to raise another number by a power?" and when they say yes and enter 2 new numbers the total adds the total from the first 2 numbers entered with the second set of numbers and so on. Can someone help me out with this problem? Here is the coding and a picture to help y'all out!
#include <iostream>
using namespace std;
int main()
{
int num;
int pow;
int p;
int power = 1;
char yesno = 'y' || 'Y';
do
{
cout << "Enter a number: ";
cin >> num; "\n";
cout << "Enter the power to raise: ";
cin >> pow; "\n";
for (p = 1; p <= pow; p++)
{
power = power * num;
}
cout << "The total is: " << power << endl;
cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while (yesno != true);
}
The problem of the ever-increasing answer is that power is not being reset inside the do-while loop, so the last value is being carried forward into the next loop. You need reset it at the top of the loop.
Another problem with the code is that the exit condition would never occur.
Try this instead:
int main()
{
int num;
int pow;
int p;
int power;
char yesno;
do
{
power = 1; // <<<<<< reset power here
cout << "Enter a number: ";
cin >> num; "\n";
cout << "Enter the power to raise: ";
cin >> pow; "\n";
for (p = 1; p <= pow; p++)
{
power = power * num;
}
cout << "The total is: " << power << endl;
cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while (yesno == 'y' || yesno == 'Y'); // <<<<< test for 'yes' response
}
When you reach line } while (yesno != true); and loop back to do {, the variable power still holds the previous num^pow. You will need to assign power = 1 after do {.
#include <iostream>
// you also need
#include <cmath> // for pow()
using namespace std;
int main()
{
// int num; Declare variables where they're used. As locally as possible.
// int pow;
// int p;
// int power = 1;
// char yesno = 'y' || 'Y'; I don't know what you were trying to do here
// the expression 'y' || 'Y' will always be true
// and evaluate to some value different from null
// wich will be assigne to yesno. But with no con-
char yesno; // sequences since it later gets overwritten by
do // cin >> yesno; There is no need to initialize
{ // this variable.
cout << "Enter a number: ";
int num;
cin >> num; "\n"; // the statement "\n"; has no effect.
cout << "Enter the power to raise: ";
int pow;
cin >> pow; "\n"; // again. no effect.
// for (p = 1; p <= pow; p++) as user4581301 has pointed out in the
// comments it is more ... natural in C
// to loop from 0 to < max:
int power = 1; // now its time to declare and define power ;)
for(int p = 0; p < pow; ++p) // notice that you can declare variables
{ // in the init-statement of a for-loop
// power = power * num; shorter:
power *= num;
}
cout << "The total is: " << power << /* endl; + 2 x '\n' gives: */ << "\n\n\n";
// cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
// } while (yesno != true); that condition will most likely always be true
// since the user would have a hard time to input
// a '\0' character, which would evaluate to false
// better:
} while(yesno == 'y' || yesno == 'Y' );
}
done.
Without clutter:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
char yesno;
do {
cout << "Enter a number: ";
int num;
cin >> num;
cout << "Enter the power to raise: ";
int pow;
cin >> pow;
int power = 1;
for(int p = 0; p < pow; ++p)
power *= num;
cout << "The total is: " << power << "\n\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while(yesno == 'y' || yesno == 'Y' );
}

cin a char into an int variable to stop a loop

I would like to read numbers into a static array of fixed size 10, but the user can break the loop by entering character E.
Here's my code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
cin >> myArray[i];
if (myArray[i] != 'E')
{
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
cout << count << endl;
system("PAUSE");
return 0;
}
However, I get the following results while entering E:
Enter upto 10 integers. Enter E to end
Enter num 1:5
5
Enter num 2:45
45
Enter num 3:25
25
Enter num 4:2
2
Enter num 5:E
-858993460
Enter num 6:-858993460
Enter num 7:-858993460
Enter num 8:-858993460
Enter num 9:-858993460
Enter num 10:-858993460
10
Press any key to continue . . .
How can I fix this code in the simplest way?
cin fails for parsing character 'E' to int. The solution would be to read string from user check if it is not "E" (it is a string not a single char so you need to use double quotes) and then try to convert string to int. However, this conversion can throw exception (see below).
Easiest solution:
#include <iostream>
#include <cmath>
#include <string> //for std::stoi function
using namespace std;
int main()
{
int myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
std::string input;
cin >> input;
if (input != "E")
{
try
{
// convert string to int this can throw see link below
myArray[i] = std::stoi(input);
}
catch (const std::exception& e)
{
std::cout << "This is not int" << std::endl;
}
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
cout << count << endl;
system("PAUSE");
return 0;
}
See documentation for std::stoi. It can throw exception so your program will end suddenly (by termination) that is why there is try and catch blocks around it. You will need to handle the case when user puts some garbage values in your string.
Just use:
char myArray[10];
because at the time of taking input console when get character then try to convert char to int which is not possible and store default value in std::cin i.e. 'E' to 0 (default value of int).
Use below code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
char myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
cin >> myArray[i];
if (myArray[i] == 'E')
{
break;
}
else
{
cout << myArray[i] << endl;
count++;
}
}
exitloop:
cout << count << endl;
system("PAUSE");
return 0;
}
Output:
Enter upto 10 integers. Enter E to end
Enter num 1:1
1
Enter num 2:E
1
sh: 1: PAUSE: not found
If you debug this, you will find all your myArray[i] are -858993460 (=0x CCCC CCCC), which is a value for the uninitialized variables in the stack.
When you put a E to an int variable myArray[i]. std::cin will set the state flag badbit to 1.
Then when you run cin >> myArray[i], it will skip it. In other words, do nothing.
Finally, you will get the result as above.
The problem is that attempting to read E as an int fails, and puts the stream in an error state where it stops reading (which you don't notice because it just doesn't do anything after that) and leaves your array elements uninitialized.
The simplest possible way is to break on any failure to read an integer:
for(int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
if (cin >> myArray[i])
{
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
If you want to check for E specifically, you need to read a string first, and then convert that to an int if it's not E.
As a bonus, you need to handle everything that's neither int nor E, which complicates the code a bit.
Something like this:
int count = 0;
string input;
while (cin >> input && count < 10)
{
if (input == "E")
{
break;
}
istringstream is(input);
if (is >> myArray[count])
{
cout << myArray[count] << endl;
count++;
}
else
{
cout << "Please input an integer, or E to exit." << endl;
}
}

Call array storing string type from one while to another

How to fix the code? I can't use vectors. I need to be able to call the names for the courses from the first while to the second one and display them.
cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
while (count <= nclass ) // while
{
//Information for the class
{
cout << "Please enter the course name for the class # "<< count << endl;
getline (cin, name);
string name;
string coursename[nclass];
for (int i = 0; i < nclass; i++) {
coursename[i] = name;
}
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
for (int x = 0; x < nclass; x++){
cout << "Here is a list of all the courses: \n" << coursename[i] << endl;
}
return 0 ;
}
you are declaring coursename as local inside loop and then using it outside so you get a compile time error (coursename is undeclared identifier).
one question: what is the role of inner for-loop????!!!
you use a for loop inside while loop through which you are assigning all the elements the same value as the string name has!!!
so every time count increments the inner for loop assigns the new value of name after being assigned, to the all elements of coursename.
count is undefined! so declare it and initialize it to 1 or 0 and take this in mind.
you wrote to the outbounds of coursname: count <= nclss to correct it:
while(count < nclass)...
another important thing: clear the input buffer to make cin ready for the next input. with cin.ignore or sin.sync
cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
string coursename[nclass];
int count = 0;
while (count < nclass ) // while
{
//Information for the class
string name;
cout << "Please enter the course name for the class # "<< count << endl;
cin.ignore(1, '\n');
getline (cin, name);
coursename[count] = name;
cin.ignore(1, '\n');
count++;
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
for (int x = 0; x < nclass; x++){
cout << "Here is a list of all the courses: \n" << coursename[x] << endl;
}
This code works!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nclass = 0, count = 1, countn = 1;
string name[100];
cout << "Please enter the number of classes" << endl;
cin >> nclass;
while (count <= nclass) {
cout << "Please enter the course name for the class # " << count << endl;
cin >> name[count];
count++;
}
cout << "Here is a list of all the courses: " << endl;
while (countn <= nclass) {
cout << name[countn] << endl;
countn++;
}
return 0;
}
Note that gave the array "name" the size of 100. Nobody is going to have 100 classes! There is no need for the for loops. It is a good practice to initialize the count and the new count which is designated by countn. Why is my answer voted down when it works?

How can you make input take strings and int? c++

is it possible, say your trying to do calculations so the primary variable type may be int... but as a part of the program you decide to do a while loop and throw an if statement for existing purposes.
you have one cin >> and that is to take in a number to run calculations, but you also need an input incase they want to exit:
Here's some code to work with
#include <iostream>
using namespace std;
int func1(int x)
{
int sum = 0;
sum = x * x * x;
return sum;
}
int main()
{
bool repeat = true;
cout << "Enter a value to cube: " << endl;
cout << "Type leave to quit" << endl;
while (repeat)
{
int input = 0;
cin >> input;
cout << input << " cubed is: " << func1(input) << endl;
if (input = "leave" || input = "Leave")
{
repeat = false;
}
}
}
I'm aware they wont take leave cause input is set to int, but is it possible to use a conversion or something...
another thing is there a better way to break the loop or is that the most common way?
One way to do this is read a string from cin. Check its value. If it satisfies the exit condition, exit. If not, extract the integer from the string and proceed to procss the integer.
while (repeat)
{
string input;
cin >> input;
if (input == "leave" || input == "Leave")
{
repeat = false;
}
else
{
int intInput = atoi(input.c_str());
cout << input << " cubed is: " << func1(intInput) << endl;
}
}
You can read the input as a string from the input stream. Check if it is 'leave' and quit.. and If it is not try to convert it to a number and call func1.. look at atoi or boost::lexical_cast<>
also it is input == "leave" == is the equal operator. = is an assignment operator.
int main() {
cout << "Enter a value to cube: " << endl;
cout << "Type leave to quit" << endl;
while (true)
{
string input;
cin >> input;
if (input == "leave" || input == "Leave")
{
break;
}
cout << input << " cubed is: " << func1(atoi(input.c_str())) << endl;
}
}
you can use like
int input;
string s;
cint>>s; //read string from user
stringstream ss(s);
ss>>input; //try to convert to an int
if(ss==0) //not an integer
{
if(s == "leave") {//user don't want to enter further input
//exit
}
else
{
//invalid data some string other than leave and not an integer
}
}
else
{
cout<<"Input:"<<input<<endl;
//input holds an int data
}