C++ homework, cant get the right output for my program - char

// Nate Banks
// Homework 2
// 10/25/2022
#include<iostream>
using namespace std;
int main()
{
char name;
int birth;
int year = 2022;
cout << "Please enter your name and year of birth:";
cin >> name >> birth;
cout << "Hi " << name << "!" << " You are " << year - birth << " years old!";
return 0;
}
What im expecting to happen is that it displays the message HI input name! you are (however old) years old!
but what really happens is: Please enter you r name and year of birth: Nate 2003
Hi N! you are 2022 years old!
Im new to c++ so I just need a quick simple fix nothing to spiffy thanks!

Related

Output won't format correctly. Creates Random Indents

I am new to C++ and programming.
I am using the CLion editor. I created a simple program for a homework assignment and I can't figure out why my out put indents every line after the second line. I have searched online and here, but most indent questions ask how to indent, not how to make your output stop indenting when I never asked it to.
Thanks in advance for any help. I appreciate it.
I tried using code to left align, but that didn't work. I also tried creating a new project and retyping it in. I still got the same result.
I also tried adding a new line break--that prevents the indent, but then I have a blank line.
I think it may be a setting---but I have no idea which setting to change.
`
#include <iostream>
#include<iomanip>
using namespace std;
int main()
{
int numberPennies, numberNickels, numberDimes, numberQuarters,
totalCents;
cout << "Please Enter Number of Coins: " << endl;
cout << "# of Quarters: ";
cin >> numberQuarters;
cout << "# of Dimes: ";
cin >> numberDimes;
cout << "# of Nickels: ";
cin >> numberNickels;
cout << "# of Pennies: ";
cin >> numberPennies;
totalCents = int((numberQuarters * 25) + (numberDimes * 10) +
(numberNickels * 5) + (numberPennies));
cout << "The total is " << int(totalCents / 100) << " dollars and "
<< int(totalCents % 100) << " cents ";
return 0;}`
The result should be left aligned, instead my output appears like this:
`Please Enter Number of Coins:
# of Quarters:13
# of Dimes:4
# of Nickels:11
# of Pennies:17
The total is 4 dollars and 37 cents
Process finished with exit code 0`
It seems like you're doing everything right, I ran this code in Visual Studio 2019 and didn't have the issue you're describing. I think that the indentation you're seeing might be a feature of your IDE.
Try running the .exe you're generating instead of using the built in console in your IDE.

C++: How can I make an integer filter with only <iostream> library?

(I don't have much english vocabulary, so sry for this weird try of english)
Hi guys! I'm new at C++ and I need to know how to create a filter code that help me at only accept int-eger numbers. I need that this code use only the 'iostream' library. This is because my teacher don't let us use another kind of library (we are new at C++ coding).
Here I put an example of what I have at this moment:
# include <iostream>
# include <limits> //I should't use this library
using namespace std;
int main() {
int value = 0;
cout << "Enter an integer value: ";
while(!(cin >> value)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl <<"Value must be an integer"<< endl << endl; //This line needs <limits>
cout << "Enter another integer value: " ;
}
}
But this code have some inconvenients:
I'm using "#include 'limits'" library and I shouldn't use it
If you enter "1asd" it takes the "1" value, give it like if its correct and it isn't true
Do you guys have any solution for this situation? Thanks in advance for your time.
You just have to check if the bytes that the user entered are numerals like below. If all the bytes of the entered string are numerals (ie between characters 0 and 9), then the entire string is an integer. Except first byte of the string can be a '+', '-', a space/tab or just the first numeral in the number. (Thanks Zett42).
std::cout << "Enter an integer value: ";
std::string res1;
std::cin >> res1;
std::string::iterator it;
for ( it = res1.begin() ; it < res1.end(); it++)
{ std::cout << "checking " << *it << ' ';
if (!( '0' <= *it && *it <= '9' )) {
std::cout << "this is a numeral\n";
} else {
std::cout << "you entered: " << *it << " -- this is *not* a numeral\n";
}
}

Isalpha() function with while loop c++

I want to create a while loop that will allow me to input a mix of string numbers until I input string that contains all characters.
Also, I have a problem with output
int main() {
string name;
string temp;
cout << "Enter your name:";
cin >> name;
cout << endl;
for(auto a:name) {
if(isalpha(a)) {
temp=name;
} else {
while(!isalpha(a)) {
cout << "Enter your name without digit:";
cin >> name;
cout << endl;
}
}
}
cout << temp << endl;
}
for(auto a:name) {
This is a loop over the characters in name, as entered after the prompt "Enter your name:". The current character is assigned to a.
if(isalpha(a)) {
temp=name;
}
If the letter is alphabetic, assign temp = name (every time the current letter is alphabetic... this is not what you want!).
else {
...if the current character (a) is not alphabetic...
while(!isalpha(a)) {
...enter a second loop, which will loop until a is alphabetic...
cout << "Enter your name without digit:";
cin >> name;
cout << endl;
}
...but a is never again assigned to. Your loop does not terminate.
You should re-work your logic. As this looks like a self-study project, I will not write the reworked loop for you, as I think you will learn much more from trying to do it on your own.

Is this simple program semantically correct? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm a beginner in C++ (4 days or so into my course) i created a small program that seems to work the way i want it to.
Quick summary:
The program asks for your name.
then asks for two numbers to add together.
displays the answer.
then asks if you want to calculate again y/n.
However, i can't help but feel like its a total train wreck in terms of formatting.
In particular the Again() function...
Inside of it, i created a loop by calling on another function if the condition was true. like so:
bool Again() {
std::cout << "Would you like to calculate again y/n?\n";
std::string answer = "";
std::cin >> answer;
if (answer[0] == 'y') {
std::cout << "Cool lets do it then \n";
PickTwo();
Again();
}
else {
std::cout << "alright, goodbye\n";
}
return 0;
}
Is it proper or improper to create a loop the way i did in Again() ?
if so, is there a right way to do it ?
This is the entire program:
#include <iostream>
#include <string>
void Greetings();
int PickTwo();
bool Again();
int main() {
Greetings();
PickTwo();
Again();
system("pause");
return 0;
}
void Greetings() {
std::cout << "Hi my name is Program, we're going to do something today. \n";
std::cout << "Whats your name?\n";
std::string Name;
std::getline(std::cin, Name);
std::cout << "Hi " << Name << ", we're going to try to do math\n";
return;
}
int PickTwo() {
std::cout << "Please pick the numbers to be added\n";
int firstNumber;
std::cin >> firstNumber;
int secondNumber;
std::cin >> secondNumber;
int Answer = firstNumber + secondNumber;
std::cout << "This are your numbers " << firstNumber << " and " << secondNumber << std::endl;
std::cout << "If we add them you have " << Answer << std::endl;
return Answer;
}
bool Again() {
std::cout << "Would you like to calculate again y/n?\n";
std::string answer = "";
std::cin >> answer;
if (answer[0] == 'y') {
std::cout << "Cool lets do it then \n";
PickTwo();
Again();
}
else {
std::cout << "alright, goodbye\n";
}
return 0;
}
Thank you in advance, knowing what NOT to do will help me fix the bad habits before they get worst.
Is it proper or improper to create a loop the way i did in Again() ? if so, is there a right way to do it ?
In a language that does not support tail recursion, your program has the potential to cause stack overflow. I would not recommend using it they way you have it coded.
It will be better to use a while loop or a do-while loop. In the loop, do whatever you need to do again.

std::cout seems to be printing out an extra "|" when called initially

I am working on a portion of my code that is suppose to output the error message correctly.
Please see below screenshot, I am using on bash
./myProgram < input3a.in | diff -a -y output3a.out -
Left hand side is what I want to get to.
For some reason an extra "|" is printed before the char array 'line' is printed. I suspected that maybe the char array 'line' is not null terminated. but it is initialize by cin.getline(); which should null terminate the char array.
Here i try to print the 'line' array in my main procedure, and it left the | sign on the line before it.
my question is. why does std::cout display this behaviour?
Thanks
EDIT,
Below is my code in question. Thanks for taking a look again.
#include "char_stack.h"
#include <iostream>
void printErrorLine(int errorSpot, int c_count, char line[]){
//Print the first line of error message char by char, at the
//same time replace char with \t or space
for(int x = 0; x <= errorSpot; x++){
std::cout << line[x];
if(line[x] != '\t'){
line[x] = ' ';
}
}
std::cout << std::endl;
//Print out the second line, if the first line does not have a
//errorSpot, then dont print it
if(errorSpot != c_count){
std::cout << line << std::endl;
}
}
char findCounterPart(char bracket){
//pass.
}
int main(int argc, char * argv[]){
char line[250]; // 250 because spec sheet detailed max 250 char per line.
char c;
int l_count = 0; // number of lines already read
int c_count; // character count in a line
char_stack S;
bool isError;
while(!std::cin.peek() == std::cin.eof()){
std::cin.getline(line, 250);
c_count = std::cin.gcount();
l_count +=1;
//std::cout<< c_count << std::endl << std::endl;
//loop through the line
for(int x = 0; x < c_count; x++){
c = line[x];
//std::cout << c << " stack size is " << S.size() << std::endl;
if (c == '(' ||
c == '{' ||
c == '['){
S.push(c);
}
else if(c == ')' ||
c == '}' ||
c == ']'){
if(S.empty()){
std::cout << "Error on line " << l_count << ": Too many " << c << std::endl;
isError = true;
}
else{
char l = S.pop();
if(l != findCounterPart(c)){
std::cout << "Error on line " << l_count << ": Read " << c <<
", expected " << findCounterPart(l) << std::endl;
isError = true;
}
}
}
if (isError){
printErrorLine(x, c_count ,line);
return 0;
}
}
}
if (!S.empty()){
c = S.pop();
std::cout << "Error on line " << l_count << ": Too many " << c << std::endl;
printErrorLine(c_count, c_count , line);
}
else{
std::cout <<"No Errors Found" << std::endl;
}
return 0;
}
Learning to be a software engineer is about breaking problems down into manageable chunks, and here we have a couple of doosies. Lets rephrase your question slightly:
I am getting unexpected characters displayed when diff the output of my program against a file containing output of a previous run. Currently I think this is because of some weird behavior of std::cout.
Well, that might be a reasonable assumption, we can't see your code so we can't know if you're doing anything peculiar.
But it would have to be: std::cout is used, well, all over the place. It just doesn't have this behavior unless your code is deliberately writing a | somewhere.
There are a number of steps we could take to resolve this:
Run the program a 3rd time in the debugger and step through until you have some ideas where the '|' is appearing,
Run the program a 3rd time to the console and observe the output,
View the output using a command like cat, less or more, instead of diff
3 is perhaps the most sensible place to start, since the file is already right there and after that #2 will give us a mk1eyeball check.
What we find is: the | does not appear in the file or the output. It's not coming from your program.
Lets create a couple of .txt files and diff them:
osmith#WOTSIT MINGW64 ~
$ echo -e 'First line\nSecond line' >test1.txt
osmith#WOTSIT MINGW64 ~
$ echo -e 'First line\nFile two line 2' >test2.txt
osmith#WOTSIT MINGW64 ~
$ diff -a -y test1.txt test2.txt
First line First line
Second line | File two line 2
When using the -y switch, between the two columns of output, diff has a line of special characters to indicate lines that changed, were inserted or deleted.

Resources