My assignment says:
---Rewrite the program by grouping the calculations into functions. In particular, you should introduce at least the following functions:
---A function named toLowerCase that takes a single character as an input parameter and returns a character. The returned value should be identical to the input unless the input is an upper-case letter, in which case the returned value should be the lower-case equivalent to that letter.
---Another function named toLowerCase, this one taking a string as an input parameter and returning a string. The returned string should be identical to the input except that all upper-case letters have been converted to lowercase.
----A function named readText that takes a string as an output parameter (no return value) and that reads multiple lines of input from cin until either hitting end-of-input or encountering an empty line. (Note: readText should not write anything to cout.)
----A function named countCharacter that takes two parameters as input and return an integer. The first input parameter will be a string and the second a character. The returned value should be the number of time that character occurs in the string (zero if the character occurs nowhere in the string). This function should work as described for all legal characters (i.e., even though this program will only use it to count lower-case letters, it should work for lower-case letters, upper-case letters, punctuation, etc.)
As you introduce each function, replace the code in main() by calls to your new functions as appropriate.
I keep getting error: expected primary-expression before char
#include<iomanip>
#include<iostream>
#include<string>
using namespace std;
void readText(string& text);
void toLowercase(string& text);
void countcharacter(string& text, char []);
char ToLowerCase();
int main (int argc, char** argv)
{
string userinput; //Initialize string name userinput
cout << "Enter text to be analyzed, ending with an empty line or end-of-input:" << endl;
readText(userinput); //Read text from user
cout << "You've entered: \n" << userinput << '\n'; // Read input, line by line, until end of input or an empty line
toLowercase(userinput); //Output user input and if upper-case, convert to lower-case
cout << "Lower case version of what you said: \n" << userinput << '\n';
countcharacter(userinput); //Count characters in userinput
ToLowerCase();
return 0;
}
void readText(string& text)
{
string line;
getline (cin, line);
while (cin && line != "")
{
text = text + line + "\n";
getline (cin, line);
}
/*for(std::string line; getline(std::cin, line) && !'\n' ; )
input += line + '\n'; */
}
void toLowercase(string& text)
{
const int ucLcOffset = 'a' - 'A';
for (int i = 0; i < text.size(); ++i)
{
char c = text[i];
if (c >= 'A' && c <= 'Z')
text[i] = text[i] + ucLcOffset;
}
}
void countcharacter(string& text, char c)
{
// Count and report on each alphabetic character
int totalCount = 0;
for (c = 'a'; c <= 'z'; ++c)
{
// Count how many times c occurs in the text
int charCount = 0;
for (int i = 0; i < text.size(); ++i)
{
if (text[i] == c)
++charCount;
}
// report on character c
cout << c << ":" << charCount << " " << flush;
if ((c - 'a') % 10 == 9)
cout << "\n";
totalCount = totalCount + charCount;
}
// How many characters are left over?
cout << "\nother:" << text.size() - totalCount << endl;
}
char ToLowerCase()
{
char c = 'A';
char Conversion;
const int ucLcOffset = 'a' - 'A';
if (c >= 'A' && c <= 'Z')
Conversion = c + ucLcOffset;
cout << "Your conversion for character A is: " << Conversion << '\n';
}
Line 28 error. 'countcharacter(userinput); //Count characters in userinput'
The line:
#inlcude<iostream>
Should be:
#include <iostream>
Syntax highlighting is your friend.
Also... countcharacter() takes two arguments:
void countcharacter(string& text, char []);
But you only provide one:
countcharacter(userinput);
#inlcude<iostream>
You spelt include wrong.
countcharacter(userinput); //Count characters in userinput
countcharacter() takes two parameters, not one.
It seems you want to count the occurrences of each lower case character ('a'-'z'). In this case you don't need to pass a second argument to countcharacter(). Change:
void countcharacter(string& text, char []);
to
void countcharacter(string& text);
and
void countcharacter(string& text, char []);
to
void countcharacter(string& text);
You will also have to declare char c in countcharacter().
It also seems you should change char ToLowerCase() to void ToLowerCase() as you don't seem to be returning anything.
I'm not a C++ guru, but the line
void countcharacter(string& text, char []);
Appears to be missing a parameter name.
Post the exact code you fed to your compiler. You wouldn't get "error: expected primary-expression before char" for what you posted, you'd get "error: invalid preprocessing directive #inlcude".
Copy-and-paste it, don't re-type it.
EDIT: fixed errror message
Related
my professor asked us to determine the number of vowels in userString without a call to the library.
I am using '\0' in a for loop to figure out when will the string the user input will come to an end because I don't know the exact size they are going to input for the string. I am a beginner programmer so please don't give me complcated answer! thanks.
I have for(int i = 0; userString[i] != '\0'; i++)
but the program is treating the space bar as a null character too so
I get a problem in the output,
if I have a space in the commend line is treats it as a null and terminates the proram
loop at the pictue of the 2 different outputs for refrence.
As you can see in output 1
When i have "MianJalal" I get 9 in the terminal but for
output 2 When I have "Mian Jalal" (with a space), it treats the space as null and gives me 4, I am aware that '\0' is space in the special chartacer in c++ but it's also null, how can I tell the program i mean null not space?
this is my code,
#include <iostream>
using namespace std;
int main()
{
int numOfVowels = 0;
int length = 0;
char userString[50]; // The string the user will input
cout << "Enter a sentence to find out how many vowels are in the sentence" << endl;
cin >> userString;
for(int i = 0; userString[i] != '\0'; i++) // '\0' means null in a string in c++; if a user doesn't use a index in a char string
{ // the program will know it's a null in syntax '\0'
if(userString[i] == 'A' or userString [i] == 'a' or userString[i] == 'i')
{
numOfVowels++;
}
length++;
}
cout << length << endl;
return 0;
}
The problem is that the operator >> uses the space as a delimiter. So when reading userString it stops at the first space. To avoid this a method could be to use istream::getline (char* s, streamsize n ) function, that reads the entire line up to the '\n' character, or the supplied size limit.
#include <iostream>
using namespace std;
int main()
{
int numOfVowels = 0;
int length = 0;
char userString[50]; // The string the user will input
cout << "Enter a sentence to find out how many vowels are in the sentence" << endl;
cin.getline(userString, sizeof(userString));
for(int i = 0; userString[i] != '\0'; i++) // '\0' means null in a string in c++; if a user doesn't use a index in a char string
{ // the program will know it's a null in syntax '\0'
if(userString[i] == 'A' or userString [i] == 'a' or userString[i] == 'i')
{
numOfVowels++;
}
length++;
}
cout << length << endl;
return 0;
}
I know there were a couple of other questions on this from a while back, but I looked over those and still couldn't figure it out. I'm trying to take user input in the form of a string, then loop through that string converting all of the uppercase to lowercase so that I can display it all in lowercase.
Where am I going wrong?
int main()
{
cout << "Enter Text: ";
string Text;
getline(cin, Text);
for(int i=0; i<Text.length(); i++)
{
if(islower(Text[i]) == false)
{
tolower(Text[i]);
i++;
}
Text[i] = Text[i];
}
cout << "Your text is: ";
cout << Text;
cout << "\n";
}
I'm very new to C++ and I'd be lying if I said I had much of an idea even where I was going wrong. Line 11, where the for loop is says that it's trying to compare two different signs, but I don't know what that means or if that's the source of my problem. Line 15 where the tolower() is says that it's 'ignoring return value of function declared with pure attribute' but I still don't know what that means either.
Please help.
A few points:
tolower returns the lowercase character if it exists ('A' becomes
'a', 'a' is unchanged, '9' is unchanged, etc.)
The line Text[i] = Text[i]; does not do anything, you want Text[i]
= tolower(Text[i]);
There is no need to check if each character is lowercase, tolower
will handle that for you
Simplified:
#include <iostream>
using namespace std;
int main() {
cout << "Enter Text: ";
string Text;
getline(cin, Text);
for (int i = 0; i < Text.length(); i++)
Text[i] = tolower(Text[i]);
cout << "Your text is: ";
cout << Text;
cout << "\n";
}
I'd suggest using the std library algorithm function transform to simplify and to make the code easier to read for you and others.
#include <iostream> //for cout and getline
#include <algorithm> //for transform
int main()
{
cout << "Enter Text: ";
string Text;
getline(cin, Text);
//This will iterate over each character [Text.begin()-Text.end()] and then
//replace it by a call to tolower with itself as a parameter
transform(Text.begin(), Text.end(), Text.begin(), ::tolower);
cout << "Your text is: ";
cout << Text;
cout << "\n";
}
EDIT:
As Remy pointed out to correct way of implenting this is by using a proxy lambda since
the behavior of std::tolower is undefined if the argument's value is
neither representable as unsigned char nor equal to EOF.
transform(Text.begin(), Text.end(), Text.begin(),
[](unsigned char c){ return std::tolower(c); });
I'd recommend looking at the ascii tables to see the codes for upper case and lower case characters.
http://www.asciitable.com/
bool islower(char in)
{
return !(char >= 'A' && char <= 'Z'); //we do this so if its a not an alphabet character we don't get false positives
}
char tolower(char in)
{
return char-'A' + 'a'; //essentially get its distance from the start of the
//alphabet and add this distance to the lowercase (only works on uppercase)
}
Its all just about working with the ascii values to get what you want since all characters are essentially integers.
My job is write a program what converts a sentence into lower and upper case.
#include <iostream>
using namespace std;
int main ()
{
int current;
string sent;
cout << "Please enter a sentence: ";
cin >> sent;
for (int i = 0; i < sent.length(); i++)
{
current = (int) sent[i];
cout << "Your sentence in all lower case: "<< sent;
cout << endl;
if (current >= 65 && current <= 90)
{
current += 32;
sent[i] = (char) current;
cout << "Your sentence in all upper case: " << sent;
}
}
return 0;
}
The output should be:
Please enter a sentence: I Eat Apples!
Sentence in all lower case: i eat apples!
Sentence in all upper case: I EAT APPLES!
However I keep getting a lowercase "i" for the lower case and the upper case I get an upper case I, how come my code doesn't print out the full sentence? I don't get what I did wrong or where the wrong doing is.
The input operator >> separates on white-space (space, newline, tab, etc.). If you want to read a whole line use std::getline:
cout << "Please enter a sentence: ";
getline(cin, sent);
On an unrelated note, please don't use magic numbers like 65 or 32. If you mean characters then use the actual character literals like 'A' or 'a' - 'A' (please note that e.g. 'a' - 'A' is not valid in all encodings, it works in ASCII which is the most common encoding, but it's really not portable). This is also assuming this is a school assignment, otherwise you should be using e.g. std::toupper and some suitable standard algorithm function.
You should have two loops. One loop will be used to convert all letters of the sentence to the lower case and the other loop will be used to convert all letters of the sentence to the upper case.
Also to enter a sentence you should use standard function std::getline. And you need to include header <string>.
For example
#include <iostream>
#include <string>
//^^^^^^^^^^^^^^^
using namespace std;
int main()
{
string sentence;
cout << "Please enter a sentence: ";
getline( cin, sentence );
//^^^^^^^^^^^^^^^^^^^^^^
cout << "Your sentence in all lower case: ";
for ( string::size_type i = 0; i < sentence.length(); i++ )
{
char c = sentence[i];
if ( c >= 'A' && c <= 'Z' )
{
c |= ' ';
}
cout << c;
}
cout << endl;
cout << "Your sentence in all upper case: ";
for ( string::size_type i = 0; i < sentence.length(); i++ )
{
char c = sentence[i];
if ( c >= 'a' && c <= 'z' )
{
c &= ~' ';
}
cout << c;
}
cout << endl;
return 0;
}
The program output might look like
Please enter a sentence: I Eat Apples!
Your sentence in all lower case: i eat apples!
Your sentence in all upper case: I EAT APPLES!
Pay attention to using the blank character ' ' instead of magic number 32 to convert letters to lower or upper case. This allows to apply the approach also to EBCDIC characters.
You could substitute the loops for range based for loops. For example
for ( char c : sentence )
{
if ( c >= 'A' && c <= 'Z' ) c |= ' ';
cout << c;
}
cout << endl;
your code is quite strange to convert to upper/lower case, there are algorithms int STL to do that easily in C++ . Check out --> How to convert std::string to lower case?
And also , as others mentioned, use getline to get your line from an input stream
Hope this help =)
The extraction operator >> considers spaces (whitespace, tabs, newline etc.) as terminating the value being extracted.
Therefore writing:
std::string str;
std::cin >> str;
If we input This is a string only This will be extracted.
To get a whole line, you could use the function std::getline by including <string> that takes an input stream as first argument, a string as second argument and optionally a delimiter as third argument:
std::string sentence;
std::cout << "Please enter a sentence: ";
std::getline(std::cin, sentence);
To convert all the characters to uppercase or lowercase, there exists a library that you can use <cctype>, it has std::toupper and std::tolower among others.
This can easily be accomplished by using a loop:
std::string sentence_upper(sentence);
for (unsigned int i = 0; i != sentence_upper.length(); ++i) {
sentence_upper[i] = std::toupper(sentence_upper[i]);
}
Or if you have a C++11 compliant compiler you can use range-based for loop:
std::string sentence_upper(sentence);
for (auto &ch : sentence_upper)
ch = std::toupper(ch);
Putting it all together:
int main()
{
// Get input from user
std::string sentence;
std::cout << "Please enter a sentence: ";
std::getline(std::cin, sentence);
// Create new string, convert to upper
std::string sentence_upper(sentence);
for (unsigned int i = 0; i != sentence_upper.length(); ++i) {
sentence_upper[i] = std::toupper(sentence_upper[i]);
}
// Output converted string
std::cout << "Your sentence in upper case:\n";
std::cout << sentence_upper << '\n';
}
This snippet of code include the string I want to display and a helper method that's sole function is to display the string, entering the text on a new line when it finds a colon. However, it is only doing that for the last colon, not the other colons
string list = ":hello:chris:";
void displayEntry(){char *colon = ":";
for (int i = 0; i<list.length(); i++) {
char *letter = &list.at(i);
if (strcmp(letter, colon) != 0) {
cout << list[i];
continue;
}
cout << "\n";
}
cout << "\n";
}
It's because strcmp is not used for comparing single characters, it compares a whole string up until it finds a NUL character.
You don't actually need char* for any of this, just use char and ==.
if (list.at(i) != ':')
I have written a code to reverse a string
#include < iostream >
#include < cstring >
using namespace std;
string Reversal(char * s);
int main()
{
char str[25];
cout << "Enter a Name :";
cin.get(str, 25);
cout << "You have entered: " << str;
cout << "\nReversed : " << Reversal(str);
return 0;
}
string Reversal(char * s)
{
int count = strlen(s);
char temp[count];
for (int i = 0; i < count; i++)
{
temp[i] = * (s + (count - 1) - i);
}
return temp;
}
Have referred below link to make cin take whitespaces as input:
How to cin Space in c++?
But the output is showing a few junk characters ? Any suggestion why so?
When you implicitly construct a std::string from temp, the latter is expected to be NUL-terminated, which it isn't.
Change
return temp;
to
return std::string(temp, count);
This uses a different constructor, one that takes an explicit character count and doesn't expect temp to be NUL-terminated.
The last character in the temp array should be null-terminated. Make it 1 longer than the size of your input string. Make the last character the null character ('\0').
string Reversal(char *s)
{
int count=strlen(s);
char temp[count+1]; //make your array 1 more than the length of the input string
for (int i=0;i<count;i++)
{
temp[i]= *(s+(count-1)-i);
}
temp[count] = '\0'; //null-terminate your array so that the program knows when your string ends
return temp;
}
The null character specifies the end of the string. Usually it is a byte with all 0 bits. If you don't specify this as the last character of your temp array, the program will not know when is the end of your array of characters. It will keep including every character until it finds a '\0'.