receives a number between 0 and 120 - prompt

I'm trying to get the programme to keep asking the person their age until the program receives a number between 0 and 120. I've set up a do while loop but i'm getting an error message, any help would be appreciated.
{
string name = get_string("What's your name?\n");
printf("Hello, %s\n", name);
sleep(1);
do
{
int age = get_int("How old are you?\n");
}
while (age < 1 || age > 120)
printf("Wow, %s you've been around for atleast %i days!\n", name, age * 365);
sleep(1);
ERROR MESSAGE
name.c:14:8: error: use of undeclared identifier 'age'
while (age < 1 || age > 120)
^
name.c:14:19: error: use of undeclared identifier 'age'
while (age < 1 || age > 120)
^
name.c:16:71: error: use of undeclared identifier 'age'
printf("Wow, %s you've been around for atleast %i days!\n", name, age * 365);
^
name.c:21:42: error: use of undeclared identifier 'age'
printf("So you're %i and from %s\n", age, town);
^
4 errors generated.
<builtin>: recipe for target 'name' failed
make: *** [name] Error 1

Declare age outside of do:
int age;
do {
age = get_int("How old are you?\n");
}
while (age < 1 || age > 120)

Related

How to read parts [duplicate]

This question already has answers here:
Why is “while( !feof(file) )” always wrong?
(5 answers)
Closed 2 years ago.
I have a problem with this program: I was able to make another draft program but it only reads the first three lines and stops. Unfortunately, the input file is not symmetrical so I should use while loops for some parts only to avoid repeating parts of the program. With strcpy I could copy the work done up to a certain point and then continue from that point on. I was trying but visual studio tells me to move the memory to the heap but I don't know how to do it ... Practically I should only extrapolate certain data from the input file and order them in an output file according to a precise line.
I also know there's a problemi with char buf[200], rec[200] because I have to allocate much more memory...
the first time in
while ( !feof(fd) ) {
fscanf(fd, "session %d (COPY MODE):\n\n", &session);
you call feof before any read so feof cannot work proprely, an easy change is to do
while (fscanf(fd, "session %d (COPY MODE):\n\n", &session) == 1) {
Out of that the mode can be something else that COPY MODE and the two \n after are not mandatory, you also do not check your next fscanf success and globaly the algorithm you use is wrong
A possible way to do the job also checking the validity of the input file is :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE * fp = fopen("summary.txt", "r");
if (fp == NULL) {
perror("cannot open summary.txt");
exit(1);
}
int session;
char mode[64];
const char * separator = "_____________________________________________";
while (fscanf(fp, " session %d (%[^)]):", &session, mode) == 2) {
if (strcmp(mode, "COPY MODE") && strcmp(mode,"ONLINE FREE MODE"))
{
fprintf(stderr, "invalid file, invalid mode '%s'\n", mode);
exit(1);
}
char line[64];
char given[64];
char recognized[64];
int registration, registration_set = 0;
int sequences, sequences_set = 0;
for(;;) {
/* read next line, bypass possible newline(s) before */
if (fscanf(fp, " %63[^\n]", line) != 1) {
if (!feof(fp)) {
perror("reading file");
exit(1);
}
*line = 0;
}
else if (sscanf(line, "number of sequences: %d", &sequences) == 1) {
sequences_set = 1;
continue;
}
else if ((*given == 0) &&
(sscanf(line, "characters given: %63s", given) == 1)) {
if (!registration_set) {
fprintf(stderr,
"registration is missing before 'characters given: %s'\n",
given);
exit(1);
}
if (!sequences_set) {
fprintf(stderr,
"sequences is missing before 'characters given: %s'\n",
given);
exit(1);
}
continue;
}
else if ((*recognized == 0) &&
(sscanf(line, "characters recognized: %63s", recognized) == 1)) {
if (!*given) {
fprintf(stderr,
"given is missing before 'characters recognized: %s'\n",
recognized);
exit(1);
}
continue;
}
if (registration_set) {
if (!*given) {
fputs("invalid file, given is missing\n", stderr);
exit(1);
}
printf("%d %d %d %s %s\n", session, registration, sequences, given, recognized);
if (!*line || !strcmp(line, separator))
break;
}
if (sscanf(line, "registration %d:", &registration) != 1) {
fprintf(stderr,
"invalid file, 'registration <n>:' expected rather than '%s'\n",
line);
exit(1);
}
else {
registration_set = 1;
*given = *recognized = 0;
}
}
}
fclose(fp);
return 0;
}
Note the space at the beginning of the format of the fscanf, that allows to bypass character considered to be space including the newline
Compilation and execution :
pi#raspberrypi:/tmp $ gcc -Wall c.c
pi#raspberrypi:/tmp $ cat summary.txt
session 1 (COPY MODE):
number of sequences: 15
registration 1:
characters given: CALOR
registration 2:
characters given: CARINO
registration 3:
characters given: SUSHI
_____________________________________________
session 2 (COPY MODE):
registration 1:
number of sequences: 15
characters given: SUSHI
characters recognized: SUSHI
_____________________________________________
session 3 (ONLINE FREE MODE):
number of sequences: 15
registration 1:
characters given: PERA
characters recognized: PFRA
registration 2:
characters given: SALON
characters recognized: SALON
registration 3:
characters given: PERRO
characters recognized: PERRO
_____________________________________________
session 4 (ONLINE FREE MODE):
registration 1:
number of sequences: 7
characters given: TORTUGA
characters recognized: TORTUGA
registration 2:
number of sequences: 4
characters given: ANAEROBIO
characters recognized: ANAERPBIO
registration 3:
number of sequences: 4
characters given: PAPELES
characters recognized: PAPELEX
pi#raspberrypi:/tmp $ ./a.out
1 1 15 CALOR
1 2 15 CARINO
1 3 15 SUSHI
2 1 15 SUSHI SUSHI
3 1 15 PERA PFRA
3 2 15 SALON SALON
3 3 15 PERRO PERRO
4 1 7 TORTUGA TORTUGA
4 2 4 ANAEROBIO ANAERPBIO
4 3 4 PAPELES PAPELEX
pi#raspberrypi:/tmp $

stuck on CS50x left aligned to right aligned mario pyramid

I have been trying to make my pyramid from left aligned to right aligned but i am confused on how to do it. This is the code i am using.
Edit: i have changed the code but i have been getting an error
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
do
{
//asks user for number between 1 and 8
height = get_int("please give height: ");
}
while (height < 1 || height > 8);
//prints rows (i)
for (int rows = 0; rows < height; rows++)
{
//prints spaces (j)
for (int spaces = 0; spaces < height - rows; spaces++)
{
printf(".");
}
printf("\n");
}
for (int hashes = 0; rows < height - rows; hashes++)
{
printf("#");
}
printf("\n");
}
user gets prompted and writes number between 1 and 8
user types 4
Expected
...#
..##
.###
####
Actual output
....
...
..
.
mario.c:24:48: error: use of undeclared identifier 'rows'
for (int hashes = 0; rows < height - rows; hashes++)
^
mario.c:24:32: error: use of undeclared identifier 'rows'
for (int hashes = 0; rows < height - rows; hashes++)
^
2 errors generated.
<builtin>: recipe for target 'mario' failed
make: *** [mario] Error 1
i am trying to print hashes and use the rows interger but for some reason the error says it is am undefined interger.
I think the error is because you're curly brackets {} in your first and second for loops are mixed up. It looks like you're trying to do three loops that are nested inside each other; however, your third loops is outside the first one because you have an extra } in the middle of your code for the second loop. The variable row is declared in the first loop and the third loop doesn't know what that means since it is outside the first loop.
Sticking to the class's recommendations about indentation helped me keep this straight.

Send array to function in BACI (C--)

I want to send an array to a function then print all of the elements. I have an error.
.LST file is:
BACI System: C-- to PCODE Compiler, 16:59 27 Oct 2005
Source file: 1.cm Fri Nov 01 03:16:20 2019
line pc
1 0
2 0
3 0
4 0 void Print(int a[])
Error near '[', line 4 of file 1.cm:
** syntax error
Because of 1 error the PCODE file will not execute
Baci reference is:
http://inside.mines.edu/~tcamp/baci/baci_index.html
C:\badosxe> bacc 1.cm Error near '[', line 4 of file 1.cm: ** syntax error>>Because of 1 error the PCODE file will not execute Pcode and tables are stored in 1.pco Compilation listing is stored in 1.lst
void Print(int a[])
{
int i;
for (i = 0; i < 5; i = i + 1)
{
cout<<a[i];
}
}
main()
{
cout << endl;
cobegin
{
int a[5] = {1,2,3,4,5};
Print(a);
}
}

Calling a Class member function in Global Scope using friend Gives 27 ERRORS

//My Header File
//Header File
#include<iostream>
using namespace std;
MyFloat rotate_right(MyFloat obj)
{
/*All that this function is supposed to do, is to return a new object, that object will
be having array elements in the order like 2.2 3.2 4.2 5.2 6.2 where the
original(object that is passed in parameter) object must be having array elements
in order like 3.2 4.2 5.2 6.2 2.2
*/
MyFloat c;
c.size = obj.size;
c.arr = nullptr;
c.arr = new float [obj.size];
c.arr[0] = obj.arr[obj.size - 1];
for(int i = 1,j=0; i < (obj.size - 1); i++,j++)
{
c.arr[j] = obj.arr[i];
}
return c;
}
class MyFloat
{
public:
MyFloat();//Default Constructor
MyFloat(int data);//Parameterized Constructor
MyFloat(MyFloat & const obj);//Copy Constructor
void input();//Filling Array
void PrintFloat();//For Displaying Array
MyFloat& operator=(MyFloat & const obj);//Assignment Operator Overloading
friend MyFloat rotate_right(MyFloat obj);/////////////This is the Function which is causing Problem/////////////
~MyFloat();//Destructor
private:
int size;//size of array
float *arr;
};
////////////This is the Cpp FILE Having Definition of All Functions
#include"My_Floats_Header.h"
MyFloat::MyFloat()
{
cout << "Default Constructor Called!" << endl;
size = 0;
arr = nullptr;
}
MyFloat::MyFloat(int _size)
{
cout << "Parametrized Constructor Called!" << endl;
size = _size;
arr = nullptr;
arr = new float [_size];
}
void MyFloat :: input()
{
for(int i = 0 ; i < size; i++)
{
cout << "Enter an Element = ";
cin >> arr[i];
}
}
MyFloat :: MyFloat(MyFloat & const obj)
{
size = obj.size;
arr = nullptr;
arr = new float [size];
for(int i = 0 ; i < obj.size; i++)
{
arr[i] = obj.arr[i];
}
}
MyFloat & MyFloat :: operator=(MyFloat & const obj)
{
size = obj.size;
arr = nullptr;
arr = new float [size];
for(int i = 0 ; i < obj.size; i++)
{
arr[i] = obj.arr[i];
}
return *this;
}
void MyFloat :: PrintFloat()
{
for(int i = 0 ; i < size; i++)
{
cout << arr[i];
}
cout << endl;
}
MyFloat::~MyFloat()
{
if(arr != nullptr)
{
delete [] arr;
}
size = 0;
}
////Cpp file having mian()
#include"My_Floats_Header.h"
int main()
{
MyFloat *floatNumber = new MyFloat(5);//declaration
floatNumber -> input();//taking input
MyFloat newfloatNumber = *floatNumber;
floatNumber = rotate_right(floatNumber);
cout << "My Float without Rotation: ";
newfloatNumber.PrintFloat();
cout << "My Float after Rotation: ";
floatNumber -> PrintFloat();
system ("pause");
return 0;
}
ERRORS THAT I'm GETTING:
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int (in line number 4)
Error C2146 syntax error: missing ';' before identifier 'rotate_right' (in line number 4)
Error C2143 syntax error: missing ';' before '{' (in line number 5)
Error C2447 '{': missing function header (old-style formal list?) (in line number 5)
Error C2143 syntax error: missing ';' before '&' (in line number 40)
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int (in line number 40)
Error C2086 'int MyFloat': redefinition (in line number 40)
Error C2761 'MyFloat &MyFloat::operator =(MyFloat &)': member function redeclaration not allowed (in line number 41)
Error C2059 syntax error: '{' (in line number 41)
Error C2143 syntax error: missing ';' before '{' (in line number 41)
Error C2447 '{': missing function header (old-style formal list?) (in line number 41)
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int (in line number 4)
Error C2146 syntax error: missing ';' before identifier 'rotate_right' (in line number 4)
Error C2143 syntax error: missing ';' before '{' (in line number 5)
Error C2447 '{': missing function header (old-style formal list?) (in line number 5)
Error C2065 'floatNumber': undeclared identifier (in line number 6)
Error C2061 syntax error: identifier 'MyFloat' (in line number 6)
Error C2065 'floatNumber': undeclared identifier (in line number 7)
Error C2227 left of '->input' must point to class/struct/union/generic type (in line number 7)
Error C2146 syntax error: missing ';' before identifier 'newfloatNumber' (in line number 8)
Error C2065 'newfloatNumber': undeclared identifier (in line number 8)
Error C2065 'floatNumber': undeclared identifier (in line number 8
)
Error C2065 'floatNumber': undeclared identifier (in line number 9)
Error C2065 'newfloatNumber': undeclared identifier (in line number 12)
Error C2228 left of '.PrintFloat' must have class/struct/union (in line number 12)
Error C2065 'floatNumber': undeclared identifier (line number 15)
Error C2227 left of '->PrintFloat' must point to class/struct/union/generic type (line number 15)
MyFloat rotate_right() probably shouldn't be in a header file. If you take it out, you should resolve (most? all?) of your errors.
My recommendation would be to make it a static method of MyFloat.
As an alternative, you could keep rotate_right() as a standalone function, and simply #include "MyFloat.h at the top of your .cpp file.
In the header file, move the class definition above the definition of rotate_right(). This will get you closer to working code. Order matters.

Why am I getting an Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12 error?

at java.lang.String.charAt(String.java:658)
at TelephoneNumberTranslator.correctFormat(TelephoneNumberTranslator.java:97)
at TelephoneNumberTranslator.getPhoneNumber(TelephoneNumberTranslator.java:61)
at TelephoneNumberTranslator.main(TelephoneNumberTranslator.java:22)
Hello,
I have read about the off-by-one error, and that is a possibility. I have fooled around with my code the best I can, though, and the results have not differed. I removed the last while loop from the correctFormat method; however, I was prompted to enter my name and then the program stopped. I even entered an extra message box at the end of the convertPhoneNumber method to see if the string just wasn't being returned for some reason, but I got no result from that either. I know that this is a common problem, but from what I have read, I am still not wrapping my head around it. This is only the fifth or sixth program I have written, though, so I'm not too flustered. Just someone pointing me on the right path that won't mind if I write them back and forth a bit would be helpful. Gracias,
Andy`
import javax.swing.JOptionPane; //Needed for user dialogue boxes
import java.io.*; //Needed for File I/O classes
/*
PROGRAM: TelephoneNumberTranslator.java
Written by Andrew Sechrist
On 10/13/15
For CPS 121 - JAVA Programming
This program requests user input for their name and a telephone number that may be a combination of alphanumeric characters.
It checks the string for correctness and converts lower case alphabetic characters to upper case. It then outputs the data.
*/
public class TelephoneNumberTranslator //This line creates the class TelephoneNumberTranslator
{
//This line creates the Main Method for the above class
public static void main(String[] args) throws IOException
{ //This line opens the body of the Main Method to begin creating the class
String userName; //For the user's name; initialized with a call to method getName
String phoneNumber; //To hold the value of the string phoneNumber
char eachSymbol; //For a specific symbol from the phone number String
userName = getName(); //Calling the getName method to obtain the user's name
phoneNumber = getPhoneNumber(); //Calling the getPhoneNumber method to obtain the user's phone number input
/*Making sure the phone number is in the correct
format with a call to the correctFormat method*/
String formattedPhoneNumber = correctFormat(phoneNumber);
//Converting the phone number correctly with a call to the convertPhoneNumber method
String convertedPhoneNumber = convertPhoneNumber(formattedPhoneNumber);
//Call method displayResults to display the results
displayResults(userName, formattedPhoneNumber, convertedPhoneNumber);
}
/**
The getName method prompts the user to enter their name
It then returns their name to the main method
#return The name the user entered is returned
*/
public static String getName()
{
String name = //For the user's name locally in the getName method
JOptionPane.showInputDialog("Please enter your name: ");
return name; //Return the user's name
}
/**
The getPhoneNumber method prompts the user to enter a phone number
It then checks the phone number for correctness with a call to the correctFormat method
It finally returns the phone number to the main method
#param getPhoneNumber
#return The phone number the user entered is returned
*/
public static String getPhoneNumber()
{
String thisNumber = //Get a phone number
JOptionPane.showInputDialog("You will be entering a telephone number.\n Make sure that it is in the format XXX-XXX-XXXX\n Any X can be any" +
" numer 0 to 9 inclusive\n or any alphabetical English letter A through Z inclusive.\n Please enter the telephone number: \n");
String phoneNumber = correctFormat(thisNumber);
return phoneNumber; //Return the phone number
}
/**
The correctFormat method receives an argument of telephoneNumber from the getPhoneNumber method
It detects any format errors and prompts the user to correct them by inputting the phone number again
It finally returns the phone number input with any formatting errors corrected to the getPhoneNumber method
#param telephoneNumber
#return the user's inputted telephone number in the correct format
*/
public static String correctFormat(String telephoneNumber)
{
int firstHyphen = telephoneNumber.indexOf('-'); //Holds position of first hyphen
int secondHyphen = telephoneNumber.lastIndexOf('-'); //Holds position of second hyphen
int stringSize = telephoneNumber.length(); //Holds the length of the telephone number string
char symbol; //To hold the referenced value in the present position of the telephoneNumber string
while (firstHyphen != 3 || secondHyphen != 7) //A while loop to make sure that hyphens are placed correctly
{
telephoneNumber =
JOptionPane.showInputDialog("The number you enter must be in the format XXX-XXX-XXXX\n It seems that you have misplaced or forgotten " +
"the hypens (-).\n They are necessary, so please re-enter a telephone number with them placed correctly: \n");
}
while (stringSize > 12) //A while loop to correct situations where there are not 12 characters in the string
{
telephoneNumber =
JOptionPane.showInputDialog("The number you enter must be in the format XXX-XXX-XXXX\n Any X can be any numer 0 to 9 inclusive\n" +
"or any alphabetical English letter A through Z inclusive.\n Please re-enter a telephone number: \n");
}
int i = 0; //An accumulator variable
char ch = telephoneNumber.charAt(i); //Holds the first char value in the phone number string
//A while loop to determine that values are either hyphens or letters or digits
while (ch != ' ')
{
ch = telephoneNumber.charAt(i); //Holds the char value in the next position of the telephoneNumber string
if (ch != '-')
{
if (!Character.isLetterOrDigit(ch)) //Prints an error message if the char is not an English letter or digit
{
telephoneNumber =
JOptionPane.showInputDialog("The number you enter must be in the format XXX-XXX-XXXX\n Any X can be any numer 0 to 9 inclusive\n" +
"or any alphabetical English letter A through Z inclusive.\n Please re-enter a telephone number: \n");
}
}
i++;
}
System.exit(0); //Terminate JOptionPane's running thread
return telephoneNumber; //Return a correctly formatted phone number
}
/**
The correctFormat method receives an argument of telephoneNumber from the getPhoneNumber method
It detects any format errors and prompts the user to correct them by inputting the phone number again
It finally returns the phone number input with any formatting errors corrected to the getPhoneNumber method
#param telephoneNumber
#return the user's inputted telephone number in the correct format
*/
public static String convertPhoneNumber(String telephoneNumber)
{
StringBuilder sb = new StringBuilder(); /**Initializing a StringBuilder class object to hold all generated values
in one accessable String*/
int i = 0; //An accumulator variable
char ch = telephoneNumber.charAt(i); //Holds the first char value in the phone number string
while (ch != ' ') //A while loop to determine whether there is another character to check
{
char symbol = telephoneNumber.charAt(i); //To hold the referenced value in the present position of the telephoneNumber string
if (Character.isLetter(symbol)) //To convert lower case alphabetic values to upper case
{
char value = Character.toUpperCase(symbol);
}
if (symbol == '-')
{
sb.append(symbol); //Hold the values of the characters in the String
}
else if (symbol == 'A' || symbol == 'B' || symbol == 'C' || symbol == '2')
{
symbol = 2;
sb.append(symbol);
}
else if (symbol == 'D' || symbol == 'E' || symbol == 'F' || symbol == '3')
{
symbol = 3;
sb.append(symbol);
}
else if (symbol == 'G' || symbol == 'H' || symbol == 'I' || symbol == '4')
{
symbol = 4;
sb.append(symbol);
}
else if (symbol == 'J' || symbol == 'K' || symbol == 'L' || symbol == '5')
{
symbol = 5;
sb.append(symbol);
}
else if (symbol == 'M' || symbol == 'N' || symbol == 'O' || symbol == '6')
{
symbol = 6;
sb.append(symbol);
}
else if (symbol == 'P' || symbol == 'Q' || symbol == 'R' || symbol == 'S' || symbol == '7')
{
symbol = 7;
sb.append(symbol);
}
else if (symbol == 'T' || symbol == 'U' || symbol == 'V' || symbol == '8')
{
symbol = 8;
sb.append(symbol);
}
else if (symbol == 'W' || symbol == 'X' || symbol == 'Y' || symbol == 'Z' || symbol == '9')
{
symbol = 9;
sb.append(symbol);
}
else if (symbol == '1')
{
symbol = 1;
sb.append(symbol);
}
else
{
symbol = 0;
sb.append(symbol);
}
}
JOptionPane.showMessageDialog(null, sb);
return sb.toString();
}
public static void displayResults(String userName, String formattedTelephoneNumber, String convertedTelephoneNumber)
{
JOptionPane.showMessageDialog(null, "Thank you for entering a phone number " + userName + ".\n The telephone number that you entered " +
"was: " + formattedTelephoneNumber + ".\n After replacing any letters that you entered to the correct keypad numbers\n your telephone " +
"is " + convertedTelephoneNumber + ".\n");
System.exit(0); //Terminate JOptionPane's running thread
}
}
In your while loops, change it from
while (ch != ' ')
to
while (ch != ' ' && i < telephoneNumber.length()-1)

Resources