#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence ="";
cin >> sentence; //aab
int i;
for (i=0;i=sentence.length();i++){
if (i<=65 && i>=90) {
sentence = sentence[i] + 32;
}
else if (i<=97 && i>=122){ //i=0,
sentence = sentence [i]-32;
}
}
cout << sentence;
return 0;
}
When I enter this code for changing cases of letters it keeps asking me to enter more although I have only one cin in the code why does that happen?
Problem one is inadvertent assignment. Look at your loop condition:
for (i=0;i=sentence.length();i++)
That assigns i rather than comparing it, resulting in an infinite loop. Use < instead of =:
for (i=0; i < sentence.length(); i++)
Problem two is you're comparing the position in the string to the character ranges rather than the character itself, and the comparison is backwards and can never be true:
if (i<=65 && i>=90)
Should be:
if (sentence[i] >= 65 && sentence[i] <= 90)
Same for the lower case range.
Finally, you don't want to change the whole sentence to one character, just that character:
sentence = sentence[i] + 32;
Should be:
sentence[i] = sentence[i] + 32;
Again, same for the lower case range.
With these changes, it seems to work, at least for single words. If you want to do entire sentences, I'd recommend using std::getline(std::cin, sentence); rather than cin >> sentence;.
Related
My Program needs to find a letter that has the most occurrences from a text file and then display the letter and the number of occurrences. Also the whole string from the text file has to be converted from lowercase to uppercase.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream inputFile;
inputFile.open("letter_count.txt");
string letter;
char ch;
char alphabet[26] = { 0 };
int counts = 0;
while (inputFile)
{
// Read file
inputFile.get(ch);
if (isalpha(ch))
{
//Make all letters upper case
toupper(ch);
//Counts number of occurrences for each letter
if (ch >= 'A' || ch <= 'Z')
{
alphabet[counts++];
}
}
}
for (int i = 0; i < 26; i++) //Displays number of occurrences for each character A-Z
{
cout << alphabet[i] << endl;
}
inputFile.close();
system("pause");
return 0;
}
toupper(ch);
doesn't change the case of ch. The toupper function returns the upper case value so you need
ch = toupper(ch);
Next
alphabet[counts++];
is clearly wrong as it doesn't use the value of ch. You need a way to convert ch into an integer so that you can use that integer to index the alphabet array. I.e. you need to convert 'A' -> 0, 'B' -> 1, 'C' -> 2 etc. Making the almost certainly true assumption that you are using the ASCII character set, you can do that with a simple subtraction
ch - 'A'
Putting that together with the incrementing code you get
alphabet[ch - 'A']++;
Finally this is wrong
for (int i = 0; i < 26; i++) //Displays number of occurrences for each character A-Z
{
cout << alphabet[counts] << endl;
}
since your loop variable is i but for some reason you used counts inside the loop. It should be
for (int i = 0; i < 26; i++) //Displays number of occurrences for each character A-Z
{
cout << alphabet[i] << endl;
}
Pay attention to the code you are writing, since the compiler will do exactly what you tell it, even if it makes no sense.
I am trying to change a series of letters into numbers with C++ and have started by making this code.
However, it appears that the math that calculates the digit1 variable is never getting executed.
Any thoughts?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int qtyofnumbers, num, digit1, counter;
char letters, upperlower;
cout << "Enter a letter: ";
cin >> letters;
for (counter = 0; counter < 8; counter++)
{
if (counter == 3)
cout << "-";
num = static_cast<int>(letters) - static_cast<int>('A');
if (0 <= num && num < 26)
digit1 = (num / 3) + 2;
if (((num / 3 == 6 ) || (num / 3 == 7)) && (num % 3 == 0))
digit1 = digit1-1;
if (digit1 > 9)
digit1 = 9;
cin >> letters;
}
cout << digit1;
return 0;
}
My guess is that the problem is in your input. Are you entering capital letters or lowercase letters? Their ASCII codes are different. So, you probably want to change the code from
num= static_cast<int>(letters)-static_cast<int>('A');
to something like
if (num >= 'a')
num = letters - 'a';
else
num = letters - 'A';
Also, as mentioned by #jtbandes, use the curly braces { and }. Whitespace does not determine scope in C++. Even if it's for only one line of code after your if-statement, it'll save you headaches in the future.
Is the static cast necessary? I recommend using a string stream or just traversing the string character by character using .at() and relying on the ascii values for conversion. http://web.cs.mun.ca/~michael/c/ascii-table.html.
The directions for my assignment are as follows:
Return the number of times that the string "hope" appears anywhere in the given string, except we'll accept any letter for the 'p', so "hode" and "hooe" count.
I am struggling to figure out how to make the third letter equal anything and still have the program identify that it is correct.
My code so far is quite obviously wrong but ill include it nonetheless.
one big problem is i can't tell the array to check if it matches the string.
int wordsFunction(string words)
{
int num = 0;
for(int i = 0; i < words.length(); i++)
{
if(words[i] == "Hope" || words[i] == "hope")
{
num++;
}
}
return num;
}
main()
{
string words;
cout << "Enter a string: ";
getline(cin, words);
cout << wordsFunction(words);
My code so far is quite obviously wrong
That is true. I wouldn't explain why your code is wrong, and go straight to a description of a fix.
Your main reads the string that allows spaces, which is good: the I/O part of your code does not need to be changed.
Now observe that to detect the word "ho*e", with * denoting any single character, at a position i in a word w, you need to check that w[i] is an 'h', w[i+1] is an 'o', w[i+3] is an 'e', and that the index i+3 is valid. This becomes a simple check:
if (i+3 < w.size() && w[i] == 'h' && w[i+1] == 'o' && w[i+3] == 'e') {
count++;
}
*Hello!
I'm making program where user enters a sentence and program
prints out how many letters there are in a sentence(Capital and non-capital).
I made a program but it prints out weird results.Please help as soon as possible. :)
include <iostream>
include <string>
using namespace std;
int main()
{
string Sent;
cout << "Enter a sentence !"<<endl;
cin>>Sent;
for(int a=0;a<Sent.length();a++){
if (96<int(Sent[a])<123 || 64<int(Sent[a])<91){
cout << "this is letter"<< endl;
}else{
cout << "this is not letter"<< endl;
}
}
}
First of all you will get one and only one word. cin >> Sent won't extract the whole line. You have to use getline in order to do this.
Second, you should use isspace or isalpha instead to check whether a character is whitespace/an alphanumeric symbol.
Third, a < b < c is essentially the same as (a < b) < c, which isn't what you meant (a < b && b < c) at all.
You can do the following with std::alpha:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string Sent;
cout << "Enter a sentence !"<<endl;
//cin >> Sent;
std::getline (std::cin,Sent);
int count = 0;
for(int a=0;a<Sent.length();a++){
if (isalpha(Sent[a])
{
count ++;
}
}
cout << "total number of chars " << count <<endl;
}
It is better to use getline than using cin>> if your input contains whitespace.
if (96<int(Sent[a])<123 || 64<int(Sent[a])<91){
This is wrong.You can't compare using this notation.
You must do:
if( Sent[a] > 96 && Sent[a] < 122 || ....
if (96 < Sent[a] && Sent[a]<123 || 64 < Sent[a] && Sent[a]<91)
This is what you want, because:
96<int(Sent[a])<123
Will evaluate 96<int(Sent[a]), as bool, then, will compare it (that is 0 or 1) with 123.
This line
if (96<int(Sent[a])<123 || 64<int(Sent[a])<91)
must be something like this
if ((96<int(Sent[a]) && int(Sent[a])<123) || (64<int(Sent[a]) && int(Sent[a])<91))
but I suggest using the function isalpha() defined in the cctype header file.
I'm doing a problem where it asks to input an account number, which consists only of four digits. This has to be accomplished with basic beginner C++.
I need to figure out a way to restrict the input of the integer to four digits. A user should be able to put in 0043 or 9023 or 0001 and it should be an acceptable value....
I think I know how to accomplish it with a string.... getline(cin,input) and then check if input.length()==4?
But I've no idea how I would even do this with an integer input.
Note that if 0043 is intended to be distinct from 43, then the input is not in fact a number, but a digit string, just like a telephone "number".
Read the line as a string input.
Check that the length of input is 4.
Check that each character in the string is <= '9' and >= '0'.
Something like:
std::string read4DigitStringFromConsole()
{
bool ok = false;
std::string result;
while (!ok)
{
std::cin >> result;
if (result.length() == 4)
{
bool allDigits = true;
for(unsigned index = 0; index < 4; ++index)
{
allDigits = allDigits && (
(result[index] >= '0') &&
(result[index] <='9')
);
}
ok = allDigits;
}
}
return result;
}
Something like this should work. Once the user enters something with exactly four characters you can validate it. The rest of the logic is up to you.
#include <iostream>
#include <string>
int main() {
std::cout << "Enter a PIN Number: ";
std::string pinStr;
while(std::getline(std::cin,pinStr) && pinStr.size() != 4) {
std::cout << "Please enter a valid value\n";
}
}
Should you want to store it in an integer form, holding the integers in an std::vector might be beneficial. You can do this easily (loop unrolling was for clarity):
#include <iostream>
#include <string>
#include <vector>
int main() {
std::cout << "Enter a PIN Number: ";
std::string pinStr;
while(std::getline(std::cin,pinStr) && pinStr.size() != 4 ) {
std::cout << "Please enter a valid value\n";
}
std::vector<int> pin;
pin[0] = pinStr[0] - '0';
pin[1] = pinStr[1] - '0';
pin[2] = pinStr[2] - '0';
pin[3] = pinStr[3] - '0';
//pin now holds the integer value.
for(auto& i : pin)
std::cout << i << ' ';
}
You can see it running here
I like your idea to use a string as the input. This makes sense because an account "number" is simply an identifier. You don't use it in calculations. By if (sizeof(input)==4) I think you are trying to check the length of the string. The correct way to do this is if (input.length() == 4). This will check that the user inputs 4 characters. Now you need to make sure that each of the characters is also a digit. You can do this easily by taking advantage of the fact that the ASCII codes for digit characters are ordered as you expect. So if (input[i] >= '0' && input[i] <= '9') will do the trick with an appropriate for loop for the index i. Also, you probably need some kind of loop which continues to ask for input until the user enters something which is deemed to be correct.
Edit:
As an alternative to checking that each character is a digit, you can attempt to convert the string to an int with int value = atoi(input.c_str());. Then you can easily check if the int is a four-or-less-digit number.
// generic solution
int numDigits(int number)
{
int digits = 0;
if (number < 0) digits = 1; // remove this line if '-' counts as a digit
while (number) {
number /= 10;
digits++;
}
return digits;
}
similar to this post.
Then you can call this function to check if the input is 4 digits.
You probably want your code to be responsive to the user input, so I would suggest getting each character at a time instead of reading a string:
std::string fourDigits;
char currentDigit;
std::cout << "Enter 4 digits\n";
for(int i = 0; i < 4; ++i)
{
currentDigit = getch();
if(isdigit(currentDigit))
{
fourDigits += currentDigit;
std::cout << currentDigit; // getch won't display the input, if it was a PIN you could simply std::cout << "*";
}
else
{
// Here we reset the whole thing and let the user know he entered an invalid value
i = 0;
fourDigits = "";
std::cout << "Please enter only numeric values, enter 4 digits\n";
}
}
std::cout << "\nThe four digits: " << fourDigits.c_str();
This way you can handle gracefully invalid character instantly. When using strings, the input will only be validated once the user hits Enter.
So I was going over how I can use an integer type to get the input, and looked at char... since it's technically the smallest integer type, it can be used to get the code... I was able to come up with this, but it's definitely not refined yet (and I'm not sure if it can be):
int main() {
int count=0;
while(!(count==4)){
char digit;
cin.get(digit);
count++;
}
return 0;
}
So, the loop keeps going until 4 characters are collected. Well, in theory it should. But it doesn't work. It'll stop at 2 digits, 5 digits, etc.... I think it could be the nature of cin.get() grabbing white space, not sure.