It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I wanna make a application like this:
this is console for example:
write_number 5
Your number is 5
How do that?
Can someone explain ?
If you're hoping to learn programming by asking questions on Stack Overflow, you're going to be at it for a long time. I would recommend getting Programming -- Principles and Practice Using C++ or Accelerated C++.
As to your question:
#include <iostream>
#include <cstdlib>
int main(int argc, char** argv)
{
std::cout << "your number is " << std::atoi(argv[1]) << '\n';
}
Please note this is not the best version of this program (eg., what if the user doesn't pass an argument, or doesn't pass a number as an argument, or passes a number larger than an int, or passes a number that is a float or double instead of an int?), but it does give you an idea.
More advanced topics -- without buying the books -- can be found at Bjarne Stroustrup's technical FAQ (Stroustrup created the original versions of C++).
Here's a basic tutorial on cin and cout ("see-in/out")
http://www.cplusplus.com/doc/tutorial/basic_io/
Use console input and output. These are exposed most simply in C++ by std::cin and std::cout:
http://www.cplusplus.com/doc/tutorial/basic_io/
#include <iostream>
int main(int argc, char* argv[])
{
int value;
std::cout << "write_number ";
std::cin >> value;
std::cout << "Your number is " << value << "\n";
return 0;
}
For how best to use these features, check out this FAQ:
http://www.parashift.com/c++-faq-lite/input-output.html
Edit
If you're trying to get command line arguments to your program, such that your session looks like this:
C:\Users\MyUserName> my_program 5
Your number is 5
Then you use the arguments passed to the main function. This is an array of all the parameters you passed to the program when you ran it:
#include <iostream>
int main(int argc, char* argv[])
{
std::cout << "Your number is " << argv[1] << "\n";
}
The arguments passed in are in string (textual) form, though. If you want to convert them to a number, so that you can do arithmatic or perform comparisons with them, here is a way to do that:
http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error
{
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
template<typename T>
T ConvertTo(std::string const& s)
{
std::istringstream i(s);
T x;
if (!(i >> x))
throw BadConversion("convertTo(\"" + s + "\")");
return x;
}
int main(int argc, char* argv[])
{
int first_parameter = ConvertTo<int>(argv[1]);
std::cout << "Your number is " << first_parameter << "\n";
return 0;
}
How about we step through this.
First, we want to ask the user for input, how would we go about doing this?
// TODO: Ask user for input.
Once we have that input, how would we go about constructing the new string?
// TODO: Make new string.
Now that we have the new string, how do we display it to the user?
// TODO: Display the string.
This leaves use with the following skeleton for you to fill out:
#include <iostream>
int main()
{
// TODO: Ask user for input.
// TODO: Make new string.
// TODO: Display the string.
return 0;
}
To accomplish this, you could use cout, cin, and string. (Of course you could do the string formatting directly in cout as well)
int num = 0;
printf("write_number ");
cin >> num;
cout << "Your number is " << num;
If you're looking to do something a little more interactive, but still want to work in the console, look into curses.
int number = 5;
cout << "Your number" << number;
Related
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 4 years ago.
Improve this question
So I've been working on command line arguments in my Computer Science class and I've been getting this:
error: unqualified-id before '{' token {
{
^
I've been trying to figure out what's wrong with it and I can't wrap my head around there being an an error after my first int statement?? Here's the code. Any guidance would be much appreciated! I'm pretty much a noob when it comes to coding.
#include <iostream>
#include <string>
#include <sstream> // for std::stringstream
#include <cstdlib> // for exit()
using namespace std;
double int_rate;
const double RULE72 = 72;
const double YDAYS = 365;
int main(int argc, char *argv[]);
{
printf("argc = %d", argc);
double amount;
double int_rate;
int days;
int years;
cout << "What is the interest rate? ";
cin >> int_rate;
years = RULE72 / int_rate;
cout << "Your money doubles in " << years << " years.";
days = years * YDAYS;
cout << "Your money doubles in " << days << " days." << endl;
cout << "Amount you would like to see double. ";
cin << amount;
cout << "Money earned by day " << (amount * 2) / days << endl;
return 0;
}
A more definitive answer to this problem would be that adding a semicolon (";"), which is treated as end-of-statement (except for the usage of \, which is for splitting lines) in C++ and many other languages... and function names ended with these "semi-colons" are treated as a function declaration... So don't confuse it with function definition which is what you want to do here...
Function declarations are the pre-defined function skeletons that do not have a body and have to be defined somewhere in the code... Or else the compiler will complain about the function not having a body...
Look here:
int main(int argc, char *argv[]); // <- Semicolon
{
// Some useful and useless code here... (but not going to work anyway, so...)
}
Here, the compiler says something like:
"Hey this function has a semicolon at its end, I know, it is a function declaration..."
And when it reaches the next line, it is like:
"Huh!, where's the name of this function, I know I got a semicolon at the previous line, so it couldn't be that!"
And the compiler finally gives an error about the body not having a declaration... So, you have two options to do...
Either do something like this (Highly recommended by everyone)...
int main(int argc, char *argv[]) // <- Semicolon removed
{
// Some useful and useless code here...
}
Or: (Not recommended, but will not cause any problems)
int main(int argc, char *argv[]); // <- Semicolon! Meaning: Declaration!
int main(int argc, char *argv[]) // Compiler says : Oh its the body (definition) of the declaration I read in the previous line...
{
// Some useful and useless code here...
}
Note: I'm sure the compiler would have pointed out to you which line is causing the error so you should try out some methods yourself because learning yourself gains you more experience than yearning for an answer...
Kind regards,
Ruks.
As #StoryTeller said:
int main(int argc, char *argv[]);
This line is causing the problem. Remove ; at the end of this line.
This question already has answers here:
How do you reverse a string in place in C or C++?
(21 answers)
Closed 7 years ago.
Hey guys I'm new here and a programming noob so bear with me here.
This is for my C++ class which sadly my teacher is terrible at teaching so many things confuse me so I need some help here.
We have a lab that is called 'Reverse Sentence' and this is what it wants In this lab.
Write the function "ReverseSentence" that takes a string parameter and changes it, by reversing it.
For example:
INPUT: the first test
OUTPUT: tset tsrif eht
The function must not use an extra string, but must reverse the elements of the input string.
#include <iostream>
#include <string>
using namespace std;
void ReverseSentence( string& inputSentence){
/* Body of Function Here */
}
int main(){
string inputSentence;
cout << "Input your sentence: ";
getline(cin, inputSentence);
cout << endl;
ReverseSentence(inputSentence);
cout << "Reversed Sentence:" << endl;
cout << inputSentence << endl;
return 0;
}
Can someone please help me what function is because I'm having trouble with it.
Just use std::reverse:
void ReverseSentence( string& inputSentence){
std::reverse(inputSentence.begin(), inputSentence.end());
}
Half of the cycle and swap.
#include<algorithm>
#include<string>
void ReverseSentence(std::string &s){
for (int i = 0; i < s.size()/2; ++i)
std::swap(s[i], s[s.size() - i - 1]);
}
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 8 years ago.
Improve this question
I've got something like this. The problem is strings must be letters only, how can I do this? I've been sitting over this for few hours now and can't find any working solution. I've tried to use answers from this topic Accept only letters but I guess I'm too dumb and still can't make it work :(
#include <string>
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
int main(void)
{
vector <string> strings;
string line;
do
{
cout << "enter string, 'stop' stops: ";
cin >> line;
strings.push_back(line);
}
while (line != "stop");
vector <string> :: iterator w;
cout << "Before sorting \n";
for (w=strings.begin(); w!=strings.end(); w++)
cout << *w << endl;
sort (strings.begin(),strings.end());
cout << "After sorting \n";
for (w=strings.begin(); w!=strings.end(); w++)
cout << *w << endl;
}
You need to add validation code. For simple cases, you can do
something like:
if ( std::find_if( line.begin(),
line.end(),
[]( unsigned char ch ) { return !isalpha( ch ); }
) != line.end() ) {
// not all letters
}
(This is really only appropriate for school projects, and won't
work for the usual network encoding, UTF-8.)
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 8 years ago.
Improve this question
I want to take argv[(2 in this example)], store it into vector and use it later in program. The problem is that no operand matches those operands std::string == int. So does that mean that the app sees '-r' as int? I'm a bit confused here.
int main(int argc, char* argv[])
{
std::vector<std::string> argList;
cout<<"argc: "<<argc<<endl;
for(int i=2; i<=argc; i++)
{
argList.push_back(argv[i]);
}
if(argList.at(2) == '-r') cout<<" Good job ";
}
There are several issues with your program:
You iterate i until i == argc, that will attempt to construct a string from argv[argc], a NULL pointer due to the requirement by C and C++ standards that argv[argc] be 0 (NULL), see this SO question. argv is an array with argc pointers to null-terminated character strings (terminated by ASCII NUL, 0), the array itself is terminated with a NULL pointer (not counted in argc). Now, in C++ you can construct a string from a pointer to a null-terminated character string, but passing a NULL pointer to a string constructor results in undefined behavior, see this SO question, also see the list of std::string constructors here, you are implicitly using constructor (4) in that list (from c-string).
You start pushing onto argList with i==2, which means argList[0] will contain argv[2], you then reference argList.at(2), which would correspond to argv[4], this is not likely what you meant.
String literals use double quotes
I've corrected these and created a working program, click here
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
vector<string> argList;
cout << "argc: " << argc << endl;
for(int i=0; i < argc; ++i)
{
argList.push_back(argv[i]);
}
cout << "Program name is " << argList[0] << endl;
if(argc > 1) {
if(argList.at(1) == "-r") {
cout << " Good job, you supplied -r\n";
} else {
cout << "Unrecognized option " << argList[1]
<< "\nUsage: " << argList[0] << " -r\n";
}
}
return 0;
}
The problem is your use of single quotes in '-r'. You want double quotes here:
if(argList.at(2) == "-r") cout<<" Good job ";
The reason is that in C++, single quotes are used for characters only. There is such a thing as a "multi-byte character constant", which is what '-r' ends up being. This is something completely different from a string constant, which is what you want.
So I am currently learning C++ and decided to make a program that tests my skills I have learned so far. Now in my code I want to check if the value that the user enters is a double, if it is not a double I will put a if loop and ask them to reenter it. The problem I have is how do I go about checking what type of variable the user enters, ex- if a user enters a char or string, I can output an error message. Here is my code:
//cubes a user entered number
#include <iostream>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
double user;
cin >> user; //user entering the number
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
Edit: I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.
Safe C++ Way
You can define a function for this using std::istringstream:
#include <sstream>
bool is_double(std::string const& str) {
std::istringstream ss(str);
// always keep the scope of variables as close as possible. we see
// 'd' only within the following block.
{
double d;
ss >> d;
}
/* eat up trailing whitespace if there was a double read, and ensure
* there is no character left. the eof bit is set in the case that
* `std::ws` tried to read beyond the stream. */
return (ss && (ss >> std::ws).eof());
}
To assist you in figuring out what it does (some points are simplified):
Creation of a input-stringstream initialized with the string given
Reading a double value out of it using operator>>. This means skipping whitespace and trying to read a double.
If no double could be read, as in abc the stream sets the fail-bit. Note that cases like 3abc will succeed and will not set the fail-bit.
If the fail-bit is set, ss evaluates to a zero value, which means false.
If an double was read, we skip trailing whitespace. If we then are at the end of the stream (note that eof() will return true if we tried to read past the end. std::ws does exactly that), eof will return true. Note this check makes sure that 3abc will not pass our check.
If both cases, right and left of the && evaluate to true, we return true to the caller, signaling the given string is a double.
Similar, you check for int and other types. If you know how to work with templates, you know how to generalize this for other types as well. Incidentally, this is exactly what boost::lexical_cast provides to you. Check it out: http://www.boost.org/doc/libs/1_37_0/libs/conversion/lexical_cast.htm.
C Way One
This way has advantages (being fast) but also major disadvantages (can't generalized using a template, need to work with raw pointers):
#include <cstdlib>
#include <cctype>
bool is_double(std::string const& s) {
char * endptr;
std::strtod(s.c_str(), &endptr);
if(endptr != s.c_str()) // skip trailing whitespace
while(std::isspace(*endptr)) endptr++;
return (endptr != s.c_str() && *endptr == '\0');
}
strtod will set endptr to the last character processed. Which is in our case the terminating null character. If no conversion was performed, endptr is set to the value of the string given to strtod.
C Way Two
One might thing that std::sscanf does the trick. But it's easy to oversee something. Here is the correct way to do it:
#include <cstdio>
bool is_double(std::string const& s) {
int n;
double d;
return (std::sscanf(s.c_str(), "%lf %n", &d, &n) >= 1 &&
n == static_cast<int>(s.size()));
}
std::sscanf will return the items converted. Although the Standard specifies that %n is not included in that count, several sources contradict each other. It's the best to compare >= to get it right (see the manpage of sscanf). n will be set to the amount of the processed characters. It is compared to the size of the string. The space between the two format specifiers accounts for optional trailing whitespace.
Conclusion
If you are a beginner, read into std::stringstream and do it the C++ way. Best not mess with pointers until you feel good with the general concept of C++.
There is no suitable way to check if a string really contains a double within the standard library. You probably want to use Boost. The following solution is inspired by recipe 3.3 in C++ Cookbook:
#include <iostream>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
double cube(double n);
int main()
{
while(true)
{
cout << "Enter the number you want to cube: ";
string user;
cin >> user;
try
{
// The following instruction tries to parse a double from the 'user' string.
// If the parsing fails, it raises an exception of type bad_lexical_cast.
// If an exception is raised within a try{ } block, the execution proceeds
// with one of the following catch() blocks
double d = lexical_cast <double> (user);
cout << "The cube of " << d << " is " << cube(d) << "." << endl;
break;
}
catch(bad_lexical_cast &e)
{
// This code is executed if the lexical_cast raised an exception; We
// put an error message and continue with the loop
cout << "The inserted string was not a valid double!" << endl;
}
}
return 0;
}
double cube (double n)
{
return n*n*n;
}
sscanf can do what you want; it returns the number of arguments properly processed. This should get you started:
//cubes a user entered number
#include <iostream>
#include <cstdio>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
string user;
cin >> user; //user entering the number
// Convert the number to a double.
double value;
if(sscanf(user.c_str(), "%lf", &value) != 1)
{
cout << "Bad! " << user << " isn't a number!" << endl;
return 1;
}
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
Other methods posted in other answers have their advantages and disadvantages. This one has issues with trailing characters and isn't "C++"-y.
I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.
You can fall back on C and use strtod
You program reads in a string and then passes it to a function that attempts to convert the string into double.
bool is_double(const char* strIn, double& dblOut) {
char* lastConvert = NULL;
double d = strtod(strIn, &lastConvert);
if(lastConvert == strIn){
return false;
} else {
dblOut = d;
return true;
}
}