// Type the determine year in the command line as an argument.
// This program then prints the months and days for that year.
//Known Error argv[1] = the first digit of year,
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void printYear(int year);
int _tmain(int argc, char *argv[]){
string str;//varible used to exit the program
if (argc == 1 ){//checks to see if the years were inputted corrected
std::cout << "Please input Year in the command line. Exiting.." << std::endl;
cout << "Please type anything to continue..." << endl;
cin >> str;
return 1;
}
int Year = 1982;
int numYears = argc-1;
cout << "Number of Argments Loaded : " << numYears << endl;
for (int x = 1; x <= numYears; x++){
Year = atoi(argv[x]);
cout << "Year : " << argv[x] << endl;
cout << "Year is " << Year << endl;
printYear(Year);
}
cout << "Please type anything to continue..." << endl;
cin >> str;
return 0;
}
I'm currently learning C++ and this is one of my assignments. I just spent a better half of a day looking into this to no avail.
printYear() has been tested with numerous years and is functional. The only remanding error left is with argv[]. It only returns the first digit of the year inputted, which is fine if you want to research years 0-9. Any tips or trick you guys mind passing me? (I'm using Microsoft Visual Studio fyi)
Command line
calender.exe 1982
returns with
Number of Arguments Loaded : 1
Year : 1
Year is 1
Repetitive code I know but I'm troubleshooting.
The problem is _tmain. If you have unicode enabled it tries to give you wide (UTF-16) characters, so every other character will be \0. To fix this you want to call it main instead.
It seems that the arguments are passed as UNICODE strings however you process them in the program as ASCII strings.
Related
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Getline jump on next cin and skip the previous cin
(1 answer)
Closed 10 months ago.
Today i started working on a quite big project and found this problem I've never found. I always used to reset the cin stream with the usage in sequence of sync() and clear(). But after i changed my compiler (a month ago i switched from standalone minGW to minGW through msys2) to have filesystem included in the std library, it seems this combination doesn't work anymore. Now I'm asking 2 different questions:
Does anyone knows why exactly? (I'm using gcc 11.2.0, just checked on my CMD)
How can I solve this problem?
Here's the example code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int number;
string s;
cout << "insert a number" << endl;
cin >> number;
cin.sync();
cin.clear();
cout << "Now insert a string" << endl;
getline(cin, s);
cout << "This is your number: " << number << endl;
cout << "This is your string: " << s << endl;
}
And here's the terminal:
insert a number
8
Now insert a string
This is your number: 8
This is your string:
Obviously as you can see it doesn't wait for my input and i think it gets my enter as a char for the string. That's why it prints what seems to be nothing (it's simply '\n')
How do I get rid of these errors?Its supposed to calculate your age based on your birth year.
This code was made by me and my friend,both of us are begginers in programming.
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofargs, char* pszArgs[]);
int CurrentYear = 2020;
int BirthYear;
cout << "Enter your birth year: "
cin >> BirthYear;
if (nBirthYear <= 0)
{
cout << "Birth year cannot be processed" <<endl;
BirthYear = 2020
}
else (BirthYear > 2020)
{
cout << "Birth year cannot be processed " <<endl;
BirthYear = 2020
}
if (nBirthYear < 2020)
(cout << "Your age is : " << CurrentYear - BirthYear <<endl;
)
cout << "Press Enter to continue..." << endl;
cin.ignore(10, '\n');
cin.get();
return 0;
these are the errors
||=== Build: Debug in Actualagefinder (compiler: GNU GCC Compiler) ===|
H:\c++\Actualagefinder\main.cpp|13|error: 'cout' does not name a type|
H:\c++\Actualagefinder\main.cpp|16|error: expected unqualified-id before 'if'|
H:\c++\Actualagefinder\main.cpp|21|error: expected unqualified-id before 'else'|
H:\c++\Actualagefinder\main.cpp|26|error: expected unqualified-id before 'if'|
H:\c++\Actualagefinder\main.cpp|28|error: expected unqualified-id before ')' token|
H:\c++\Actualagefinder\main.cpp|30|error: 'cin' does not name a type; did you mean 'main'?|
H:\c++\Actualagefinder\main.cpp|31|error: 'cin' does not name a type; did you mean 'main'?|
H:\c++\Actualagefinder\main.cpp|32|error: expected unqualified-id before 'return'|
||=== Build failed: 8 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
In C++, all executed code has to be within a function.
I.e. it should look like
int main(int nNumberofargs, char* pszArgs[])
{
/* code */
}
yours starts with a prototype, followed by orphaned code.
int main(int nNumberofargs, char* pszArgs[]);
/* code */
That is why the compiler complains that it expects a known type (for a declaration) where you have your code line starting with cout (which you not unreasonably expect to be already declared).
Other lines, which are not necessarily statements, can be local or global variable definititions, the latter being possible outside of functions. That is why the compiler does not complain about them.
The first issue you need to fix is the int main() declaration. By putting the semi-colon: int main(int nNumberofargs, char* pszArgs[]); you are telling the compiler that it has reached the end of the command, without doing anything. To fix this, like in your if statements, you must encapsulate everything in the after the declaration in curly braces.
Thus, your program becomes:
#include <cstdio>
#include <cstdlib>
#include <iostream>
int main(int nNumberofargs, char* pszArgs[])
{
// Put your stuff in curly braces
}
Your next bug is in your if statements. To put it simply, if statements don't work like that in C++.
Here is what if statements should be like:
if(something){
// Do something here
}
else if(something else){ // If there are more than one possible condition, use else if
// Do something else
}
else{ // If none other condition is satisfied
// Do something
}
Notice that you cannot have if twice (you can if you have nested if statements (like if statement inside if statement)
Those are the main problems in your program. The rest are small errors. For example, in many places a ; is missing. In other places, you call on undeclared variables:
if (nBirthYear < 2020) // This was probably a typo, nBirthYear is not declared
And in one place you have an ( which is a typo: (cout << "Your age is : " << CurrentYear - BirthYear <<endl;
Also, there is some unnecessary code, like the first two lines (they are not being used).
Nevertheless, here is a working version of your program:
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofargs, char* pszArgs[]){
int CurrentYear = 2020;
int BirthYear;
cout << "Enter your birth year: " << endl;
cin >> BirthYear;
if (BirthYear <= 0)
{
cout << "Birth year cannot be processed" <<endl;
BirthYear = 2020;
}
else if(BirthYear > 2020)
{
cout << "Birth year cannot be processed " <<endl;
BirthYear = 2020;
}
else if (BirthYear < 2020){
cout << "Your age is : " << CurrentYear - BirthYear << endl;
}
cout << "Press Enter to continue..." << endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}
As the comments said, it would be recommended to look again at whatever resources that you used to make this program, you must have your fundamentals down. Make sure that you know what every part of your programs do, and put comments to remind yourself in the future. I'll try to make this answer concise to help you understand, but you really should go back through what you've read.
Additionally, make sure that you're resources are relatively new, because a lot has changed in C++ since it was created.
Okey as I've recently started to read about C++ and try to go with the book I'm having Programming Principles and practice Using C++ 2nd version.
I'm a total newbie so this is probably why, but here goes.
Okey so in the book they have you implement a header .h file instead of the (iostream) etc. So it just have all those for the start as the book doesn't want us to focus on those libraries in the start of the learning.
So i implemented it and used it (not sure if this is related to the problem). Anyway at page 77, I'm getting stuck.
Basically it's a wrong value that's getting entered and it's supposed to just show -1(or 0) as the int gets a false value, etc Carlos(letters, not an integer) so the int doesn't get a correct value so the code that is supposed to work (and show 0 or -1 as it's an incorrect value that's entered) is this according to the book:
#include "std_lib_facilities.h"
using namespace std;
int main()
{
cout << "Please enter your first name and age\n";
string first_name = "???"; // string variable // ("???” means “don’t know the name”)
int age = –1; // integer variable (–1 means “don’t know the age”)
cin >> first_name >> age; // read a string followed by an integer
cout << "Hello, " << first_name << " (age " << age << ")\n";
}
and this is what i wrote:
#include "std_lib_facilities.h"
using namespace std;
int main()
{
cout << "Please enter your first name and age" << endl;
string First_Name = "???";
int Age = -1;
cin >> First_Name >> Age;
cout << "Hello, " << First_Name << "(age" << Age << ")" << endl;
keep_window_open();
return 0;
}
However, the result with visual c++ for me is a crash when i for example write 22 Carlos.
According to the book it's supposed to output Hello, 22 (age -1)
But for me it just crashes after i enter the word Carlos as value for age...
I don't get a a error or anything when i run and compile it, but it crashes after when i give the false value for age.
What am i doing wrong?
add: I know i can use a string to get it to work, however I'm just interested in why it doesn't work as I'm following this book i wish to follow it without having these kind of problems as it's intended to work.
Here is a gif when im doing it:
http://imgur.com/a/ERjhz
Solution: To use system("pause"); instead of keep_window_open();
however it's still annoying to read the book with the knowledge that the code in the book doesn't work always :(
Well it is isn't a problem but too fast to be noticed by our eyes.
i am adding the function definition of keep_window_open()
inline void keep_window_open()
{
cin.clear();
cout << "Please enter a character to exit\n";
char ch;
cin >> ch;
return;
}
As you can see it simply takes the character input from the us
Forward you will learn about input stream and its buffer
So when you input a character in place of integer there is error flagged in the stream(background) and the only one of the characters input is used(in your case 'C' is used for flagging).
I am using input as Carlos 22
So now the input stream is still having characters 'a','r','l','o','s',22
so now the 'a' is used as a input for keep_window_open function
and the program ends without waiting for a input from you
So there is no error or crash but since the character is already there for input for keep_window_open function so its kind of really fast
The problem is in keep_window_open. It's a tricky function that is very hard to get absolutely right. You can replace it with this code that sidesteps the problem but only works on Windows:
inline void keep_window_open()
{
system("pause");
}
or with this slightly more complicated code that tries to take more cases into account:
inline void keep_window_open()
{
cout << "Please enter a character to exit\n";
if (!cin)
{
cin.clear();
cin.ignore(120, '\n');
}
char ch;
cin >> skipws >> ch;
}
(This assumes you don't enter lines longer than 120 characters. Replace 120 with numeric_limits<streamsize>::max() if you want it to be free from arbitrary limits. Other functions from std_lib_facilities.h do use 120 in this situation. You many or may not have to add #include <limits> directive to your program).
I have tested in a couple of cases and it appears to work with both correct and incorrect input to the program, but use it at your own risk. It still may or may not work correctly if your program requires more complicated input.
A good rule is to always except that the end users is idiots, so you need to write the program in a way that can handles all kinds of inputs without crashing. Therefore always read input numbers as std::string and then try convert it to int, short, double, unsigned int or what ever datatype you are using.
Your code should look like:
#include <cstdlib>
#include <exception>
#include <iostream>
#include <stdexcept>
#include <string>
int main(int argc, char **argv)
{
int age;
std::string first_name;
std::string input_age;
std::cout << "Please enter your first name and age: " << std::endl;
std::cin >> first_name >> input_age; // Read the age as 'std::string'
try
{
age = std::stoi(input_age); // Try to convert age from 'std::string' to 'int'
std::cout << "Hello, " << first_name << " (" << age << ")" << std::endl;
}
catch(std::invalid_argument& ex) // 'std::stoi()' will throw 'std::invalid_argument' if it's not able to convert 'std::string' to 'int'
{
std::cerr << "Unable to convert input value ('" << input_age << "') to 'int'" << std::endl;
std::cerr << "Debug info: " << ex.what() << std::endl;
}
catch(std::out_of_range& ex) // 'std::stoi()' will throw 'std::out_of_range' if 'std::string' is too small or too big to store in a 'int'
{
std::cerr << "The input value (" << input_age << ") is out of range, please input a value inside the range" << std::endl;
std::cerr << "Debug info: " << ex.what() << std::endl;
}
return EXIT_SUCCESS;
}
So it's nothing to do with code, it's something to do with input.
when i for example write 22 Carlos.
The problem is that the code is asking for First_Name then Age, Not Age then First_Name. So when you put 22 for First_Name, the .exe got confused.
for example lets say I did this
int y = 0;
cout << "Give me INT: ";
cin >> y;
cout >> "You put: " >> y;
And when I run the program and put this for input
Give me INT: ghaisewofasd
*crashed*
This is a problem because the user is giving a string for when the code is asking for a int.
So for your case, instead of writing 22 Carlos, just write Carlos 22.
Also keep in mind, this book maybe not so correct, because it shouldn't print out Hello, (22). Now a days stuff like that crash if that happens, maybe it was a older version of C++.
I'm sitting with a challenging homework in C++ and would be really thankful for some help here!
My program need to calculate how many years it will take for an optional yearly deposition with revenue to reach a specific savings limit.
I just can't see what's wrong and have tried debugging with no help.
It doesn't really help neither that i'm totally new to C++ and MVS 2015.
I don't know if it's the math or the programming itself that is wrong.
Static typing is foreign to me since I usually use python.
Also VS don't give much information and the program just stops after asking for revenue input.
Any suggestions?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main()
{
int deposit;
int max_savings;
double revenue;
double change_factor;
double year = 0;
double geometric_sum;
cout << "Choose a yearly deposition:\n";
cin >> deposit;
cout << "Set your max saving-goal:\n";
cin >> max_savings;
cout << "set a revenue in percent:\n";
cin >> revenue;
change_factor = 1 + (revenue / 100);
geometric_sum = ((double)deposit * (pow(change_factor, year) - 1)) / (change_factor - 1);
while (geometric_sum < max_savings)
year++;
cout << "Your saving-goal will be in " << year << " years!" << endl;
cout << "Your account balance will then be " << geometric_sum << " dollars!" << endl;
return 0;
}
pow(change_factor, year) - 1
year is set to 0. Any value at the power of 0 is 1. 1 - 1 = 0. Basically you are multiplying with 0.
I'm currently working on the book "C++ Primer Plus" and doing some of the programming excersis.
As it seems, I'm having a problem with Xcode(4.3.3) because following code doesn't work how it's supposed to work:
#include <iostream>
#include <string>
struct car
{
std::string maker;
int year;
};
int main()
{
using namespace std;
cout << "How many cars do you wish to catalog? ";
int nCars;
(cin >> nCars).get();
car* aCars = new car[nCars];
for (int i = 0; i < nCars; i++)
{
cout << "\nCar #" << (i + 1) << endl;
cout << "Please enter the make: ";
getline (cin, (aCars + i)->maker);
cout << "\nPlease enter the year made: ";
(cin >> (aCars + i)->year).get();
}
cout << "Here is your collection: \n";
for (int i = 0; i < nCars; i++)
{
cout << (aCars + i)->year << " " << (aCars + i)->maker << endl;
}
delete [] aCars;
return 0;
}
The problem is, I don't have the chance to enter any maker. The program directly goes to the point where I have to enter the year, even though I'm using "(cin >> nCars).get();" to get rid of the newline character.
Am I overlooking something?
Thanks in advance!
I suspect that you may be running on windows and the two-byte newlines are hitting you. You may be able to improve things (for lines that aren't ridiculously long) with ignore:
cin >> nCars;
cin.ignore(1024, '\n');
Note that since you rely on stream numeric processing, entering a non-numeric year such as QQ will result in the programming just finishing without asking for any more input.
You don't need to do math on the years so treat them as strings instead of integers. Then if you need to you can do validation of each year after you get the input.
Ok, guys..I found the problem.
The console within Xcode doesn't work as expected when using cin.get().
I tried the same code in the terminal as well as with Visual Studio (Win 7) and the program works perfectly.
Anyway, thank you all for your advices. I'll try consider them the next time. :)
Cheers!