error: expected primary-expression before '.' token - c++

I am currently teaching myself C++ using A C++ for Dummies All-In-One; second edition. TO create this program I am using Qt. I understand it to be a good practice to organize objects and classes in your header files and prospectively your member functions in a .cpp file built in addition to the main.cpp. In this regard I try to run the exercises in this book as such but just recently encountered the following error.
expected primary-expression before '.' token
This error occurs on Lines 31, 32, and 37 so they appear to be relevant to my class member functions specifically.
My main.cpp
#include "controlinginput.h"
#include <QtCore/QCoreApplication>
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// just a basic name-entering
string name;
cout << "What is your name?";
cin >> name;
cout << "Hello " << name << endl;
/* now you are asked for a number
but the computer will allow you to enter anything*/
int x;
cout << endl << "Enter a number! Any Number!" << endl;
cin >> x;
cout << "You choose " << x << endl;
/* now youll be asked for a number again
but the computer will only allow numbers */
cout << endl<< "This time you will ONLY be able to enter a number! " << endl;
cout << "SO, Pick a number! any number!" << endl;
string entered = ControlingInput.enterOnlyNumbers(); // ###Error###
int num = ControlingInput.stringToANumber(entered); // ###Error###
cout << endl << "You entered " << num << endl; // value is displayed
//Now finally we enter the password
cout << endl;
cout << "Please enter a password" << endl;
string password = ControlingInput.EnterPassword(); // ###Error###
cout << "shh... your password is " << password << endl;
return a.exec();
}
I did some research to find that this error indicates a pretty broad range of misuse of syntax. Unfortunately I was unable to find an instance that resembled mine specifically; I was hoping to get some insight from some of the more experienced programmers. If this is a simple issue that is on account of negligence on my end I apologize in advance and appreciate the feedback. I learn better if it gave me allot of trouble as opposed to a little..
Because these include my member functions I have also included my header file and .cpp
controlingInput.cpp (I have included my header file and iostream and sstream here but for some reason the editor was giving me problems on here)
using namespace std;
ControlingInput::ControlingInput()
{
}
int ControlingInput::stringToANumber(string MyString)
{
istringstream converter(MyString); //Holds the string that was passed to this function
int result; //Holds the integer result
//perform the conversion
converter >> result;
return result; //function completes and returns converted string
}
string ControlingInput::enterOnlyNumbers()
{
string numbAsString = ""; // this holds our numeric string
char ch = getch(); // This gets a single character from our user
//Says to keep gettting characters from our user untill user presses enter
while (ch != '\r') // \r is the enter key
{
//This says to add characters only if they are numbers
if (ch >= '0' && ch <='9')
{
cout << ch; // show
numbAsString += ch; // add character to the string
}
ch = getch(); // get the next character from the user
}
return numbAsString;
}
string ControlingInput::EnterPassword()
{
string numbAsString = ""; //this will hold our password string
char ch = getch(); // this gets a single char from our users just like before
//keep gettting characters from the user until enter/return is pressed
while (ch != '\r'); // \r is the enter or return key
{
//for security passwords are displayed as asterisks instead of characters
cout << '*';
//add character input into the password string
numbAsString += ch;
//Get the next character from the user
ch = getch();
}
return numbAsString; // return the user input from this function
And Here is my controlingInput.h
#ifndef CONTROLINGINPUT_H
#define CONTROLINGINPUT_H
#include <iostream>
using namespace std;
class ControlingInput
{
public:
int stringToANumber(string MyString);
string EnterPassword();
string enterOnlyNumbers();
};
#endif // CONTROLINGINPUT_H
Thanks in advance for any feedback.

You are attempting to call instance variables with the class itself as if they were static (which would still be invalid syntax). For this to work properly you need an instance of ControlingInput.
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ControlingInput ctrlInput; //Create instance
...
string entered = ctrlInput.enterOnlyNumbers();
int num = ctrlInput.stringToANumber(entered);
cout << endl << "You entered " << num << endl; // value is displayed
...
string password = ctrlInput.EnterPassword();
cout << "shh... your password is " << password << endl;
return a.exec();
}

Related

Why can't I successfully run the following hangman game console code? I could successfully run the same code in devc++

error message.png
These are the errors
1."message": "cannot open source file \"iostream\"",
2.#include errors detected. Please update your includePath. Squiggles are disabled for this
translation unit (C:\Users\USER\first.cpp).
3.cannot open source file "cstdlib"
4.cannot open source file "ctime"
5.cannot open source file "string"
AND
This is my code
#include <iostream>
#include <cstdlib>
#include<ctime>
#include <string>
using namespace std;
const int MAX_TRIES=5;
int letterFill (char, string, string&);
int main ()
{
string name;
char letter;
int num_of_wrong_guesses=0;
string word;
string words[] =
{
"india",
"pakistan",
"nepal",
"malaysia",
"philippines",
"australia",
"iran",
"ethiopia",
"oman",
"indonesia"
};
//choose and copy a word from array of words randomly
srand(time(NULL));
int n=rand()% 10;
word=words[n];
// Initialize the secret word with the * character.
string unknown(word.length(),'*');
// welcome the user
cout << "\n\nWelcome to hangman...Guess a country Name";
cout << "\n\nEach letter is represented by a star.";
cout << "\n\nYou have to type only one letter in one try";
cout << "\n\nYou have " << MAX_TRIES << " tries to try and guess the word.";
cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
// Loop until the guesses are used up
while (num_of_wrong_guesses < MAX_TRIES)
{
cout << "\n\n" << unknown;
cout << "\n\nGuess a letter: ";
cin >> letter;
// Fill secret word with letter if the guess is correct,
// otherwise increment the number of wrong guesses.
if (letterFill(letter, word, unknown)==0)
{
cout << endl << "Whoops! That letter isn't in there!" << endl;
num_of_wrong_guesses++;
}
else
{
cout << endl << "You found a letter! Isn't that exciting!" << endl;
}
// Tell user how many guesses has left.
cout << "You have " << MAX_TRIES - num_of_wrong_guesses;
cout << " guesses left." << endl;
// Check if user guessed the word.
if (word==unknown)
{
cout << word << endl;
cout << "Yeah! You got it!";
break;
}
}
if(num_of_wrong_guesses == MAX_TRIES)
{
cout << "\nSorry, you lose...you've been hanged." << endl;
cout << "The word was : " << word << endl;
}
cin.ignore();
cin.get();
return 0;
}
/* Take a one character guess and the secret word, and fill in the
unfinished guessword. Returns number of characters matched.
Also, returns zero if the character is already guessed. */
int letterFill (char guess, string secretword, string &guessword)
{
int i;
int matches=0;
int len=secretword.length();
for (i = 0; i< len; i++)
{
// Did we already match this letter in a previous guess?
if (guess == guessword[i])
return 0;
// Is the guess in the secret word?
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
Your compiler cannot find the header files that you're including, though since you're just including headers from the standard library, there's most likely something wrong with your installation, or your environment. It could be that you're just confusing a C compiler with a C++ compiler (such as clang and clang++), or perhaps you're using a compiler that doesn't actually ship with a standard library, as is also the case with clang on Windows, which uses MSVC's standard library.
You can figure that out by trying to include a header from the C standard library, such as "stdlib.h", and see if the compiler can find it. If it can, then you're just using the wrong compiler, and if it can't, then you either lack a standard library, or your environment isn't set up properly and your compiler can't find it, but without knowing what compiler you're using, and how you're invoking it, I can't really give a detailed answer.

Logic error when checking if input is alphanumeric

The purpose of this program is to check if the character entered by the user is alphanumeric. Once the void function confirms correct entry then it is passed to string test to output a message. I know it's not great coding but it has to be done this way.
I keep getting a logic error & I can't figure out why? Can someone please help?
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
void get_option(char& input);
/**
Takes character entered user input and loops until correct answer
#param y character entered by user
#return to main() once valid entry received
*/
string test(char);
/**
Takes checks character entered user input and loops until correct answer
#param y alphanumeric character entered by user
#return to main() once valid entry received
*/
int main()
{
char y;
//call get_option to prompt for input
get_option(y);
//call test after user input is valid
test(y);
return 0;
}
void get_option(char &x)
{
cout << "Please enter an alphanumeric character: ";
cin >> x;
while (!(isdigit(x)||islower(x)||isupper(x)))
{
cout << "Please enter an alphanumeric character: ";
cin >> x;
}
}
string test(char y)
{
if (isupper(y))
{
cout << "An upper case letter is entered!";
} else if (islower(y)) {
cout << "A lower case letter is entered!";
} else if (isdigit(y)) {
cout << "A digit is entered!";
}
return "";
}
I got the program to work perfectly by changing the return type of the test(char) function:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
void get_option(char& input);
/**
Takes character entered user input and loops until correct answer
#param y character entered by user
#return to main() once valid entry received
*/
int test(char); //Changed from string to int
/**
Takes checks character entered user input and loops until correct answer
#param y alphanumeric character entered by user
#return to main() once valid entry received
*/
int main()
{
char y;
//call get_option to prompt for input
get_option(y);
//call test after user input is valid
test(y);
return 0;
}
void get_option(char &x)
{
cout << "Please enter an alphanumeric character: ";
cin >> x;
while (!(isdigit(x)||islower(x)||isupper(x)))
{
cout << "Please enter an alphanumeric character: ";
cin >> x;
}
}
int test(char y) //Also changed from string to int
{
if (isupper(y))
{
cout << "An upper case letter is entered!";
} else if (islower(y)) {
cout << "A lower case letter is entered!";
} else if (isdigit(y)) {
cout << "A digit is entered!";
}
return 0;
}
(Testing was on JDoodle using the C++14 compiler.)
(Also, tested using Xcode. Still works)
When I tried it in my setup (g++ 6.4, cygwin), I did not get any output. When I added << endl to the output lines, the output showed up.
I suspect you're experiencing the same problem.
string test(char y)
{
if (isupper(y))
{
cout << "An upper case letter is entered!" << endl; // Add endl
}
else if (islower(y))
{
cout << "A lower case letter is entered!" << endl;
}
else if (isdigit(y))
{
cout << "A digit is entered!" << endl;
}
// This does not make sense but it is syntactically valid.
return 0;
}
JiveDadson is right. The problem was the return 0 line. It causes undefined behavior. Changing the that line to
return "";
fixes the output problem, endl or not. Having the endl is nicer but is not necessary. Fixing the return statement is the most important task.

Assigning the "Enter Key" value to a string [C++]

In this rather simple exercise I have to receive an user input, store said input into a string, pass the string to a function by reference and finally modify the string so that every character is "parsed" by the toupper() function.
However, should the user insert 'q' as input, the program stops saying "Bye" OR if he just presses the Enter Key, the program is supposed to say something like "Hey, this string is empty".
Now the real problem here is in the last part since my code won't manage the case where the user inputs only the Enter Key value (to be honest, even if I just text a bunch of spaces followed by the Enter Key, nothing happens)
void uppercase(std::string &);
int main(){
using namespace std;
string ex2;
cout << "Exercise 2" <<endl;
while(ex2!="Bye"){
cout << "Enter a string(q to quit): ";
cin >> ex2;
cout << "Was: " << ex2 << endl << "Now is: ";
uppercase(ex2);
}
return 0;
}
void uppercase(std::string &str){
using namespace std;
if(str[0]=='\n')
cout <<"Empty string dude!" << endl;
else{
if(str.length()==1 && str[0]=='q'){ //press 'q' to exit program
str="Bye";
cout << str;
}
else{ //uppercase
for(int i=0;i<str.length();i++){
str[i]=(toupper(str[i]));
}
cout << str <<endl;
}
}
}
I also tried the compare() function and even to compare the whole string to null (pointless, but still worth a shot) and to the string "";
Sorry for the bad interpretation of your problem, trying
if( (str.length()==1 && str[0]=='q') || str.length() == 0)
{}
May help you out of the problem

Creating an encryption program with a choice of three methods! It has issues I am not sure how to fix

#include <iostream>
#include <string.h>
#include <string>
#include <fstream>
using namespace std;
int get_ascii_int(char ch);
int get_offset_ascii(char ch2, int offset);
//int print_string_ints(string test_string);
int method3_substitution_abc();
//above are the function declarations
int main()
{
string test_string;//input of string
char ch = 0;//used in method1
char ch2 = 0;//used in method2
int index1 = 0;//used in for loop method1
int index2 = 0;//used in for loop method2
int offset = 0;//input of how much to offset
int new_ascii = 0;//the new ascii with offset
int ascii_value1 = 0;//the ascii value of the char
int option;//the menu choice of encryption method
int decision;//the decision to save or display
ofstream method1;//method 1 text file
ofstream method2;//method 2 text file
ofstream method3;//method 3 text file
string test_string_copy;//copy of string method 2
//Below is a description of the methods of encryption
cout << "There are three methods of encryption, listed below, to choose from: " << endl;
cout << "1. Converting characters into the corresponding ASCII values. " << endl;
cout << "2. Shifting characters right/left using the ASCII value of the characters ";
cout << "and a set offset amount. " << endl;
cout << "3. Using a reverse alphabet, so each letter will be replaced with the letter ";
cout << "on the opposite end of the alphabet. For example, A would become Z. " << endl;
cout << "Which encryption method would you like to use, 1, 2, 3? ";
cin >> option;
switch (option)
{
case '1':
method1.open("method1.txt");
cout << "Input a word or name: ";
getline(cin, test_string);
for (; index1 < test_string.size(); index1++);
{
ascii_value1 = get_ascii_int(test_string[index1]);
}
cout << "Would you like to display the file or save it, enter 1 for display or 2 for save?";
cin >> decision;
if (decision == '1')
{
cout << "The encrypted code is " << ascii_value1 << endl;
}
else
{
if (method1.is_open())
{
method1 << "The encrpyted code is " << ascii_value1 << endl;
method1.close();
}
else
cout << "Unable to open file." << endl;
}
break;
case '2':
method2.open("method2.txt");
cout << "Input a word or name: ";
getline(cin, test_string);
test_string_copy = test_string;
for (; index2 < test_string_copy.size(); index2++);
{
new_ascii = get_offset_ascii(test_string_copy[index2], ch2);
}
cout << "Would you like to display the file or save it, enter 1 for display or 2 for save?";
cin >> decision;
if (decision == '1')
{
cout << "The encrypted code is " << new_ascii << endl;
}
else
{
if (method2.is_open())
{
method2 << "The encrypted code is " << new_ascii << endl;
method2.close();
}
else
cout << "Unable to open file." << endl;
}
break;
case '3':
method3.open("method3.txt");
method3_substitution_abc();
break;
}
return 0;
}
//listed below are the function definitions
int get_ascii_int(char ch)
{
return ((int)ch);
}
int get_offset_ascii(char ch2, int offset)
{
int new_offset_value;//the value after adding the determined offset to the ascii value of the letter
new_offset_value = (int)ch2 + offset;
(char)new_offset_value;
return (new_offset_value);
}
//int print_string_ints(string test_string)
//{
//for (int i = 0; i < test_string.size(); i++)
//{
//(int)test_string[i++];
//}
//return 0;
//}
int method3_substitution_abc()
{
char test_string[100];
cout << "Enter a name or phrase: ";
cin >> test_string;
if (isupper((int)test_string))
{
int stalpha = 65;//start of alphabet
int endalpha = 90;//end of alphabet
char b[100];//array to reverse the alphabet
for (int i = 0; test_string[i] != '\0'; i++)
{
b[i] = endalpha - (test_string[i] - 65);
}
}
else if (islower((int)test_string))
int stalpha = 97;//start of alphabet
int endalpha = 122;//end of alphabet
char b[100];//array to reverse the alphabet
for (int i = 0; test_string[i] != '\0'; i++)
{
b[i] = endalpha - (test_string[i] - 97);
}
return 0;
}
I am trying to write this encryption program. And I am just getting really confused on why it won't run.
For example the switch statement is not running correctly, it will go to the correct case and then skip the input of the string?
This is my first experience with C++ so I struggle to debug.
I am having issues with saving the file to a text file after the user chooses to save or display? It has to be done after every case in the switch statement.
I also know the for loops I am using are not correct for method 1 and 2? Could someone check those out and tell me what the issue is. I am pretty sure it has to do with the parameters for the for loop.
And I don't know if I should use a string or an array for this? (In the part where the user inputs a string
At least the first problem you've identified (with the switch statement) is pretty simple and clear.
You've defined option as an int, so when you read it it's read as an integer. That means if the user enters 1, it'll have the value 1, which is different from the value '1'. '1' is a character that will (for example) print as 1, but its value is actually 49 in most character sets.
You have two obvious choices: either change option to be a char, so it'll be read as a character instead of an integer, or else change the values in the switch statement from '1', '2', etc., to just 1, 2, etc.
At a guess, the problem you're seeing from getline is a fairly common one when you mix a string extractor (e.g., cin >> my_string;) with std::getline. The string extractor extracts a string from the stream, but leaves the new-line character in the stream buffer. Then when you call std::getline, it reads that new-line as an empty string, so it doesn't wait for you to enter more input.
If you really have to mix the two this way, you probably want to add a call to std::cin.ignore to read and ignore any data up to and including the new-line character. Then when you call std::getline, it'll actually read some data.

How I can manage to keep white space in my String from user input

I'm coding a little console application in C++ and in it I take a string from the user:
cin >> themainstring;
int si = 0;
while (themainstring[si] != '+' || themainstring[si] != '-' ||
themainstring[si] != '*') {
if (themainstring[si] == '+' || themainstring[si] == '-' ||
themainstring[si] == '*') {
lmnopt = themainstring[si];
break; // while
}
si++;
}
int strlenthestring = themainstring.size();
lmnop1 = themainstring.substr(0, si);
lmnop2 = themainstring.substr(si + 1, strlenthestring);
So for example, when I give this input:
ilove+programming
I want to try and cut the string when I see +, - and *. which works fine.
However I want my code to do the same when I input:
ilove + programming (white spaces after and before arithmetical operator)
I have messed around with the WS but I couldn't understand the logic.
Actually the main problem of mine is about C++'s space logic. Why it thinks the space will explode the string input?
I'm not sure I've understood this question completely correctly, however I thought I'd pitch in with some help.
First off, when it comes to looking through strings, C++ has a great set of functions as standard that does that. Point your browser to: Basic String Library.
This contains all the functions you can carry out on a string in C++.
Secondly, something else you need to be aware of, is that you are using std::cin to read user input from the keyboard. By default, cin ignores white spaces, so for example, the following code:
string inputString;
cin >> intputString;
cout << "Input String is: " << inputString << endl;
and let's assume you entered Hello World in as your user input, the program would only output "Hello"
So what you need to do is to use getline. Which allows for whitespaces in your user inputs. And you use it as follows:
std::getline(cin, inputString);
So to give an example where it all gels together:
#include <iostream>
#include <sstream> // for istringstream
#include <string>
using namespace std;
int main(int argc, char * argv[])
{
string inputString;
cout << "Please Enter String: ";
getline(cin, inputString);
cout << "\n" << endl;
cout << "InputString is: " << inputString << endl;
// So you can do something like this
string searchTerm("+");
// Find first of is an operating you can carry out
// on a string so you don't have to use loops.
cout << "Position: " << inputString.find_first_of(searchTerm) << endl;
int pos = inputString.find_first_of(searchTerm);
string part1 = inputString.substr(0, pos);
string part2 = inputString.substr(pos + 1, inputString.length());
cout << "Position of + is " << pos << endl;
cout << "part 1 is: " << part1 << endl;
cout << "part 2 is: " << part2 << endl;
}
Now I know I've only done this with the + sign, but it should serve as a starting point to getting to where you want to be.
Hope all this helps.