string,char comparison in c++ - c++

*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.

Related

C++ Loop for String

I am struggling to create a loop for getting input from user. The input must push_back() each instance.
#include <iostream>
#include <array>
#include <cstring>
#include <vector>
#include <string>
#include <string.h>
using namespace std;
int main()
{
vector <string> bookQ = { "what","book","is","that","you","are","reading" };
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
int x = 0;
for (x != '1') { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl; //
cin >> x; //
getline(cin, input); //
bookQ.push_back(input); //
} //
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
Your for loop is missing the declaration and (iteration) expression parts:
for (declaration-or-expression; declaration-or-expression; expression)
so it should have looked like this:
for (;x != '1';) {
which is generally written as
while (x != '1') {
That would cause problems though since it would not stop directly when the user entered 1.
You are also comparing an int with a char ('1'), so in order to exit the loop, the user would have had to enter 49 (the ASCII value for 1), not 1.
You are also mixing formatted input (cin >> x) with unformatted input (getline). I suggest that you stick to one only.
Example:
while(cout << "Enter 1 to stop\n", getline(cin, input) && input != "1") {
bookQ.push_back(input);
}
Assuming you meant that input is a string, then you've made a few mistakes with types. First of all, you've used wrong type for variable x, you used int which is integer type, and the type string is required. Secondly, when comparing x with '1' you used single quotes, which define the type of variable as char, not string. To make 1 a string you should use double quotes, like so "1". Besides that, you have used for(condition), which is incorrect syntax. You should use while(condition). Also, when your loop iterates, the x variable is the input book name, and input variable is always an empty string, so I would suggest replace input with x everywhere. The working code is below.
P.S. I am not sure whether you want "1" to be in the final vector, so I haven't changed that
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> bookQ = {"what", "book", "is", "that", "you", "are", "reading"};
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
string x;
while (x != "1") {
cout << "Enter 1 to stop" << endl;
cin >> x;
bookQ.push_back(x);
}
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
simply check if input is 1 everytime the user enters somthing, and when it does = 1, simply break loop.
string x;
while (true) { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl;
cin >> x;
if (x == "1"){
break;
}
getline(cin, x);
bookQ.push_back(x);
}
}
First, your for syntax is wrong. You want a while loop instead, or in this case a do..while loop would make more sense. Also, you are pushing the user's input into the vector before validating what the input actually is.
Second, x is an integer, but '1' is a character whose ASCII value is number 49. Your loop will never end, because != will always be true. Since you want the user to enter number 1 to stop the loop, you need to drop the quotes:
Third, what is the point of pre-populating bookQ? Just declare the bookQ without any initial data, and then cout the entire question as a normal string. This way, after the user is done entering input, the vector will contain only the user's input and nothing else.
Try something more like this:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
vector <string> bookQ;
string input;
cout << "what book is that you are reading" << endl;
do {
cout << "Enter a book, or 1 to stop" << endl;
getline(cin >> ws, input);
if (input == "1") break;
bookQ.push_back(input);
}
while (true);
for (size_t i = 0; i < bookQ.size(); ++i) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}

Printing words vertically

So I'm just starting in C++, so I'm not familiar with the language, though I do have knowledge of C. I'm trying to print words vertically. Here is the problem given.
Create an array of 25 strings.
Use a sentinel loop that reads from cin until the array is full or the end of input is reached
(when the user presses Ctrl-D), whichever comes first.
After the sentinel loop is over, use a for loop to move through the array.
Remember not to travel farther than the last array element that was input.
Print one array element (one string) followed by a newline
Use a for loop to move through the characters of the string you just printed
print one character followed by a newline
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
char word;
int count = 0;
cout << "Enter a word: (press Ctrl-D to quit)";
cin >> word;
int array1[25];
while (!cin.eof())
{
count = count + 1;
cout << "Enter a word: (press Ctrl-D to quit)";
cin >> word;
} //end while
for (word = 0; word <= array1[count]; word++)
{
cout << 'end1' << 'end1' << "There were " << count << "Words Entered" << 'end1';
}
} //end main
Code is rough, it compiles, but when it is in an infinite loop with numbers comes out after the texts.
Just for the hell of it
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
int main() {
string word;
int count = 0;
vector<string> arrayOfStrings;
cout << "Enter a word: (press Ctrl-D to quit)";
while(cin >> word){
if(count < 25){
arrayOfStrings.push_back(word);
count = count + 1;
cout << "Enter a word: (press Ctrl-D to quit)";
} else {
cout << "25 strings was entered";
break;
}
}//end while
for ( int j = 0; j < arrayOfStrings.size(); j++ ){
cout << '\n' << '\n' << $j << "-st string entered " << arrayOfStrings[j] << '\n';
}
}//end main
This code reads exactly 25 strings, remembers them, and even outputs them later.
This is just an educational example, which basically ignores memory managment
I strongly suggest not to use this in any actual code.
It took me about 5 mins to write this.
There are a few errors in this code - perhaps if you are familiar with C, then quickly write a version in C and translate it to a more modern "C++ like" version. Perhaps look into std::string and std::vector to make life even easier.
int array1[25]; needs to store strings, therefore it is of the wrong type.
The while (!cin.eof()) loop needs to also check that it doesn't go over the bounds of the above array (i.e. at most 25 words).
The for (word = 0; word <= array1[count]; word++) loop that needs to loop exactly n times, where n is the number of words inputted, i.e. in the above while loop.

C++ - Cin.fail when space on begining

I need help with cin.fail when it starts with a space.
This is what I mean.
#include <iostream>
#include <math.h>
using namespace std;
int main ()
{
char b[80];
int e,d,v,m=0;
for(int i=0;i<80;i++)
{
b[i]=0;
}
cout << "Insert number in binary:" << endl;
cin >> b;
v=0;
for(int i=0;i<80;i++)
{
if(b[i]=='1' || b[i]=='0' || b[i]=='\n')
{
v++;
}
else if(b[i]!=0 || b[i]!='\0' || b[i]==' ')
{
cout << "Error" << endl;
return 0;
}
}
e=v-1;
d=0;
m=0;
for(int i=0;i<v;i++)
{
m=(b[i]-48)*(pow(2,e));
d=d+m;
e=e-1;
}
cout << "His number in decimal: "<< d << endl;
return 0;
}
When there is something like 1010 it OK, it will give me number.
If it contains other number - 2,3 etc.. it will fail, its OK
But when it get something like _101010 .. programm will still proceed and it will give me number, but I need it to fail. So I need something like .. when b contains 1 0 or \n, programm will continue, otherwise it will fail. But when I put in \n like
if(b[i]=='1' || b[i]=='0' || b[i]=='\n') - its not working .. I mean, programm fails in any case ...
Sorry for asking on this "stupid" question, but I am doing it for hours and still didnt figure it out .. Thanks guys.
cin >> b; will skip leading whitespace and then read the next word. That's how it is designed.
If you want to read an entire line of input, use getline instead.
It will also be much easier, and a lot safer, if you read into a std::string instead of a fixed size char b[80];. If you ever happen to read more than 80 characters into that, you're toast.

Remove/ignore everything except characters in a Cstring

I am trying to get read in some text about 100 char long or less and then strip it of spaces, digits, special char, etc.. I was thinking about ways to go about doing this but I think I must have forgotten most of what I know about cstrings and such. I was originally trying to just take in basic characters and copy them into a new string but 1. I couldn't figure out how to write it so my compiler doesn't hate me and 2. I'm pretty sure I don't want the new, stripped string to have blanks in it (I'm pretty sure my code so far would cause that to happen, if it even worked).
char * userText="";
char * justCharTxt;
cout << "Enter text: " << endl;
cin.getline(userText, STRING_SIZE);
for (int i = 0; i < strlen(userText); i++){
if (((userText[i] >= 'a') && (userText[i] <= 'z')) ||
((userText[i] >= 'A') && (userText[i] <= 'Z')))
*justCharTxt = userTxt[i];
}
Some guidance on this issue would be awesome. Thanks!
Just use a std::string, no need to fiddle around with char arrays or pointers.
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string line;
getline(std::cin, line);
line.erase(
std::remove_if(line.begin(), line.end(),
[](char c) {return !isalpha(c, std::locale());}),
line.end()
);
std::cout << line << '\n';
}
you need to init your strings, i.e., reserve a buffer
you need to increment the dest pointer.
#include <iostream>
using namespace std;
int main(){
int const STRING_SIZE=20;
char userText[STRING_SIZE*2]="";
char justCharTxt[STRING_SIZE]="";
char * txtPt = justCharTxt;
cout << "Enter text: " << endl;
cin.getline(userText, STRING_SIZE);
for (int i = 0; i < strlen(userText); i++){
if (((userText[i] >= 'a') && (userText[i] <= 'z')) ||
((userText[i] >= 'A') && (userText[i] <= 'Z')))
*(txtPt++)= userText[i];
}
cout << justCharTxt << endl;
return 0;
}
$ clang++ justit.cpp
$ ./a.out
Enter text:
ab123 a
aba
Your char arrays do not have enough memory, and they are const.
char userText[STRING_SIZE];

Receiving integers, but also want to test for char

Say I am looking to receive a series of numeric values and read them into an int, but I also want to test if the user hit key 'x'.
I am sure I am missing something obvious, and have tried a few things but seem to be stuck.
This is what I have so far...
cout << endl << "Enter key (or 'x' to exit): ";
cin >> key;
if (key == 'x') { cout << "exiting";}
// continue on...
You need to read into a string and then convert that to an integer. In outline:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
string s;
cout << endl << "Enter key (or 'x' to exit): ";
getline( cin, s );
if ( s == "x" ) {
// do exit stuff
}
else {
istringstream is( s );
int n;
if ( ! is >> n ) {
// report not an integer
}
else {
// do something with n
}
}
}
It depends on how key is declared.
If key is an int, you can only test for numbers, of course.
How about the following outline of an algorithm:
int n = 0
bool xentered = false
while (not xentered and there is one more character before EOF)
if that character is 'x' then xentered = true
else if it is a digit
n = 10*n + numeric value of the digit
else
error
I leave the task to translate that to the programming language of your choice. :)