C++ Passing a local variable [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
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.
Improve this question
I can not figure out where the pointer is wrong in this code. However, I receive the error that the code does not have a pointer-to function.
#include <iostream>
using namespace std;
char uppercase (char ch) {
if ((ch >= 'a') && (ch <= 'z')) {
return ch - 'a' + 'A' ;
cout << "Your capital letter is " << ch << endl;
} else {
return ch;
cout << "Your original letter is: " << ch << endl;
}
}
int main(int& ch){
cout << "Please enter a lowercase letter between a to z: ";
cin >> ch;
char uppercase;
char outChar;
char inChar;
outChar = uppercase(inChar);
system("pause");
}

int main(char&) is not strictly-conforming. It may be provided by the implementation but I don't know of any platform doing this. On a hosted implementation, use int main() or int main(int argc, char** argv) instead.
Building up on the 1st note, declare ch in the function as a local variable and use char not int:
char ch;
Or remove it completely, as described in the 4th point.
You call uppercase on an uninitialized variable (inChar), resulting in undefined behavior because uppercase reads from it. Remove the ch variable and use cin on inChar instead.
You should probably exchange the return ch; with the cout-statement in the uppercase function. The cout-statement is dead code, meaning it will never be executed because the function returns beforehand.

you have local variable with same name as function name: uppercase
get rid of local variable
also fix main function to following signature.
int main(int argc, char *argv[])
{
....
}
ex:
#include <iostream>
using namespace std;
char uppercase (char ch) {
if ((ch >= 'a') && (ch <= 'z')) {
return ch - 'a' + 'A' ;
}
else {
return ch;
}
}
int main(int argc, char* argv[]){
cout << "Please enter a lowercase letter between a to z: ";
char inChar;
cin >> inChar;
char outChar = uppercase(inChar);
return 0;
}

I can see quite a few problems in your code:
Read Why System is evil. In short words, using system("pause") tends to be problematic. There are many other ways to make your code stop (e.g. another cin).
As one of the above comments stated, the general way of opening the main program is by using int main() or int main(int argc, char** argv).
Let's say that your code works... Then you're asking for an executable input "ch" which after that is changed again by asking the same input again during the program's run-time! I proppose that you use point 2. and what #cad said.
The true answer to your problem! You are using as an input to uppercase(char) a variable that has not been filled "InChar", but the character you are filling by user input is "ch".
Hope this helps.

Related

Error: expected unqualified-id before '{' token { [closed]

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.

if conditions, when i want to second argument [closed]

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
#include<fstream>
#include <iostream>
#include<string.h>
using namespace std;
int main(int argc, char* argv[])
{
string s = "all";
string t = "top";
for (int i=1; i<argc ; i++)
{
if( i == 2 && (argv[i] != s) && (argv[i] != t))
{
cout<<"INVALID MODE"<< endl;
}
if( i ==1 && (argv[i] != int))
{
cout<<"INVALID PHRASE LENGTH"<< endl;
}
}
}
I know this is horribly wrong, but is there away to do this ? im trying to say that when i =2, meaning argument 2 in a command line, is not all, and not top, to print out InValid mode
along with that, how would i test if an argument is not an integer and if it is not an integer to print out “INVALID PHRASE LENGTH” , but how would i test if the first argument is an integer or negative number
Not sure if you are aware, but when you run (sorry for running on windows)
program.exe arg1 arg2
then argv[0] is program.exe, argv[1] is arg1, argv[2] is arg2, so careful what you call the 1st and 2nd argument, meaning argv[1] is indeed the first string after the binary name, but only because of C++ indexing that starts from 0.
From what you are trying to achieve there is no need for the loop and iterating over the arguments.
#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, char* argv[])
{
string s = "all";
string t = "top";
if (argc >= 3 && ! (argv[2] == s || argv[2] == t)) {
cout << "INVALID MODE" << endl;
}
}
There are plenty of questions answering parsing a string into int.
As said here though, picking up C++ beginner book is a better time investment than trying what compiles..

How to convert first letter to uppercase in c++? [closed]

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 5 years ago.
Improve this question
I have a Structure
struct StudentRecord{
char StudentFamilyName[20]
}gRecs[50];
cout << "Family Name: ";
cin >> gRecs[50].StudentFamilyName;
char str[20];
str[20] = toupper(gRecs[i].StudentFamilyName[0]);
cout << str;
What i want to do is to store the first letter of family name as
upper case and the rest as lower case? How do I do that?
I used toupper but when I implement it doesnot work. Could anyone help me out? Thank you.
Note: This was an exam question.
Here's how to capitalize a string using character arithmetic:
#include <iostream>
#include <string>
using namespace std;
string ToCapitalize(string input)
{
if (input.length() > 1 && input[0] >= 'a' && input[0] <= 'z')
{
input[0] -= 32;
}
return input;
}
int main() {
std::string StudentFamilyName("smith");
cout << StudentFamilyName << std::endl;
cout << "Capitalized: " << ToCapitalize(StudentFamilyName) << endl;
}
Your problem isn't with toupper. There are a couple of them, actually.
cin >> gRecs[50]
gRecs is size 50, so index 50 is out of bounds. To insert into the first record you would use
cin >> gRecs[0].StudentFamilyName;
Second record: gRecs[1], etc.
Next,
char str[20];
str[20] = toupper(str[0]);
You declare str in which nothing is populated, and then call toupper on it.
And the index ([20]) is the 21st character (which is out of bounds). You are attempting to convert the 21st character in the str toupper.
What you need is something like:
// i is the index into your student records array, possibly in a loop
cin >> gRecs[i].StudentFamilyName;
gRecs[i].StudentFamilyName[0] = toupper(gRecs[i].StudentFamilyName[0]);

C++ using arguments ARGV [closed]

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.

In short I really struggle with syntax, can somebody help me fix this? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
so i need to read in a file, then create a word count and a character count for each time the character appears using an array. each word ends with whitespace, comma, period, etc. also i need to put a tolower and an equation to set the letters to the right array with an x-'a' function or something like that.
list of errors from puTTy(crappy program i know but it's required)
project8.cpp: In function âint main()â:
project8.cpp:17: error: âfile1â was not declared in this scope
project8.cpp:18: error: expected â;â before âwhileâ
project8.cpp:36: error: expected â}â at end of input
#include <iostream>
#include <string>
using namespace std;
int in_word = false;
int word_count = 0;
char ch;
char low_case;
int char_count[26];
int i;
int main()
{
for (i=0; i<26; i++)
char_count[i]=0;
cin.get(file1.txt)
while('\n' !=(ch=cin.get(file1.txt)))
{
if (' ' == ch || '\n' == ch || '\t' == ch)
in_word = false;
else if (in_word == false)
{
in_word=true;
word_count++;
}
else low_case=tolower(ch);
char_count[int(low_case)-int('a')]++;
}
cout << file1.txt;
cout << words << " words" << endl;
for (i=0; i<26; i++)
if(count[i] !=0)
cout << count[i] << " " << char(i+'a') << endl;
}
The first problem is that you haven't declared file1. It is somewhat unclear what file1.txt really is meant to be: The way it is written, it seems to be an object of type with a member called, txt of type char* or char[N] (with a constant N). From the looks of it, you actually wanted to open a file named file1.txt. This would look like so:
std::ifstream in("file1.txt");
After that you would, of course, use in instead of std::cin to read from the file. For example you could use
for (char c; in.get(c); ) {
// ...
}
to read each individual character of the file and process it appropriately.
Let's play compiler!
You cannot name a variable file1.txt, call it file1
Also, you forgot the semi-colon ; at the end of the line, so
cin.get(file1.txt)
should be
cin.get(file1);
I don't quite know where you are defining this variable, so you may be missing a declaration like
const char* file1="file1.txt";
Furthermore, you start trying to access some variable count after your for-loop here:
count[i]
Did you mean to use char_count?