Error in C++ String Program - c++

This program I am making has the user enter a string and a character and then displays the number of times that character appears in the string. For some reason every time I run this program it always says the character appears 0 times in the string. I need some help identifying the problem and fixing it. Thanks!
#include <cstdlib>
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main(int argc, char *argv[])
{
string input;
char character;
int charCount = 0;
cout << "Enter a string:" << endl;
getline(cin, input);
cout << "Enter a character:" << endl;
cin >> character;
int i = input.find(character);
while (i < 0)
{
charCount++;
i = input.find(character, (i + 1));
}
cout << character << " appears in the string, " << input << ", " << charCount << " times." << endl;
system("PAUSE");
return EXIT_SUCCESS;
}

Your issue is in the loop condition
int i = input.find(character); // if the character is in the string, it will return a number i > 0
while (i < 0) // will not enter loop
{
charCount++;
i = input.find(character, (i + 1));
}
Also, charCount is going to increase with every character you encounter in the string based on this logic.

Related

I am having some trouble with if function with char

Here, When I input CO2, it is processing the 'else' statement and if I input anything else it is still the same
I tried changing 'co2' to "co2" but then it doesn't even work
int main(int nNumberofArgs, char* pszArgs)
{
char symb[5];
cout << "Enter Symbol: ";
cin >> symb[5];
if (symb[5] == 'co2')
{
cout << "This is Carbon-Dioxide" << endl;
}
else
{
cout << "Error" << endl;
}
return 0;
}
Your code is written all wrong.
The statement char symb[5]; declares a fixed sized array that can hold 5 char elements max. But when you do cin >> symb[5];, you are not reading up to 5 chars into the array, you are reading a single char into the 6th slot of the array, corrupting surrounding memory.
Also, symb[5] == 'co2' is not the right way to compare the contents of the array. You are comparing the 6th (invalid) char against a single multi-byte character, you are not comparing the whole content of the array against a multi-character string.
Try something more like this instead:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char symb[5];
cout << "Enter Symbol: ";
cin.get(symb, 5);
if (strcmp(symb, "co2") == 0)
{
cout << "This is Carbon-Dioxide" << endl;
}
else
{
cout << "Error" << endl;
}
return 0;
}
That being said, using a std::string instead of a char[] is better:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string symb;
cout << "Enter Symbol: ";
cin >> symb;
if (symb == "co2")
{
cout << "This is Carbon-Dioxide" << endl;
}
else
{
cout << "Error" << endl;
}
return 0;
}

Traversing an Inputted String and Returning a Specific Amount of Letters Within the String

I am working on a program that has the user input a letter then a string. Once the string is inputted the program should traverse the string and return the amount of the specific letter within the string. Here is the code I have so far:
#include <iostream>
using namespace std;
void countLetters(char letter[]);
/**********************************************************************
* Prompts the user for a line of input (using getline),
* calls countLetters(), and displays the number of letters.
***********************************************************************/
int main()
{
char letter[256];
countLetters(letter);
return 0;
}
/**********************************************************************
* Function to return the number of letters in a string.
***********************************************************************/
void countLetters(char Letter[])
{
char text[] = " ";
int count = 0;
cout << "Enter a letter: ";
cin >> letter;
cout << "Enter text: ";
cin >> text;
cin.getline(text, 256);
for (int i = (sizeof(text) / sizeof(text[0]) - 2); i >=0; i--)
{
if(text[i])
{
count++;
}
cout << "Number of '" << letter << "'s: " << count << endl;
}
}
/*
The output should be:
Enter a number: e
Enter a string: Hello, programming is fun
Number of 'e's: 1
*/
I have tried researching this and have found no help through this method of counting the amount of letters within the string the user inputs. Any help is appreciated, thank you.
Most issues have been pointed out in the comments. Here's a fixed version:
#include <iostream>
using namespace std;
void countLetters();
/**********************************************************************
* Prompts the user for a line of input (using getline),
* calls countLetters(), and displays the number of letters.
***********************************************************************/
int main()
{
// You create an array in the function, don't need one here, too
// char letter[256];
countLetters();
return 0;
}
/**********************************************************************
* Function to return the number of letters in a string.
***********************************************************************/
void countLetters()
{
// Your method creates an array of only 2 bytes
//char text[] = " ";
char text[256];
int count = 0;
// You forgot to declare letter
char letter;
cout << "Enter a letter: ";
cin >> letter;
// Reading the char leaves a new line. Consume. cin.ignore is another way
cin.getline(text, 256);
cout << "Enter text: ";
cin.getline(text, 256);
// Overly complicated
//for (int i = (sizeof(text) / sizeof(text[0]) - 2); i >=0; i--)
for (int i = 0; text[i]; i++)
{
// Compare to letter
if (text[i] == letter)
{
count++;
}
// This needs to be outside the loop
//cout << "Number of '" << letter << "'s: " << count << endl;
}
cout << "Number of '" << letter << "'s: " << count << endl;
}
In C++, it's almost always better to use std::string instead of raw char arrays, but I'll assume this is an assignment and arrays are required.

Practice in dealing with character arrays that end in the null terminator

Write a program that ask user to enter any sentence, up to a maximum of 50 characters. The program will then tell how many words are in the sentence and how many characters are in the sentence. Do not count the null character. The program will then display the sentence backwards. Program must use one function that will determine how many words are in the sentence and pass this information back via a return value function.
Sample output follows:
Enter some sentence:
This is fun!
Your sentence has 3 words.
And your sentence has 12 characters.
Your sentence backwards is as follows:
!nuf si sihT
*****I have most of it done just need a little help with counting characters and making the function work*****
#include <iostream>
#include <string>
using namespace std;
int Words(char Line[]);
int main ()
{
string text;
cout << "Enter some Sentence: ";
getline(cin, text);
text = string(text.rbegin(), text.rend());
cout << "Your sentence backwards is as follows: " << text << endl;
return 0;
}
int Words (char Line []);
{
int CharCount = 0;
const int Size = 50;
char Sentence [Size];
int WordCount = 0;
cout << "Enter Some Sentence: ";
cin.getline(Sentence, 50);
for (int i =0; Sentence[i]!='\0'; i++)
{
if (Sentence[i] == ' ')
{
WordCount++;
}
}cout << "The number of words = " << WordCount+1 <<endl;
return 0;
}
You can use an istringstream constructed from the user input sentence coupled with the stream extraction operator to count the words.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int words(string sentence)
{
istringstream in{sentence};
string one;
int count = 0;
while(in >> one)
++count;
return count;
}
int main()
{
cout << words("just two") << '\n';
cout << words("A whole bunch of words!") << '\n';
cout << words("ONE!!!!") << '\n';
return 0;
}

to_string and convert.str() not declared in scope

I am having an issue trying to convert a number into a string. The purpose is for error checking to make sure the number is of a specific length. I have tried using both to_string() and convert.str() functions but get the same error back when trying to compile.
I am using MinGw g++ to compile and realize I need to tell it I want the C++11 standard, which I believe I have done. My compiler code is as follows:
NPP_SAVE
CD $(CURRENT_DIRECTORY)
C:\MinGW\bin\g++ -std=c++11 "$(FULL_CURRENT_PATH)" -o "$(NAME_PART).exe"
cmd /c $(NAME_PART).exe
Now assuming that is correct, my code for using to_string() is as follows:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
int book_code = 0;
cout << "Please enter the four digit book code: ";
cin >> book_code;
string code = to_string(book_code);
while (!(cin >> book_code) || code.length() != 4){
cin.clear();
cin.ignore(10000, '\n');
cout << "That is not a valid code." << endl;
cout << "Please enter the four digit book code: ";
}
}
And my code for using convert.str() is as follows:
int main() {
int book_code = 0;
cout << "Please enter the four digit book code: ";
cin >> book_code;
ostringstream Convert;
convert << book_code;
string code = convert.str();
while (!(cin >> book_code) || code.length() != 4){
cin.clear();
cin.ignore(10000, '\n');
cout << "That is not a valid code." << endl;
cout << "Please enter the four digit book code: ";
}
}
Neither of these was successful and both returned
error: 'to_string' was not declared in this scope
Am I missing something obvious?
In MinGW std::to_string() does not exist, you should declare your own implementation.
std::string to_string(int i)
{
std::stringstream ss;
ss << i;
return ss.str();
}
I recommend you to use MSYS2, it is more actualizated and you can avoid this type of problems.
Edit:
Checking the dot position in double:
#include <iostream>
#include <sstream>
#include <string>
std::string to_str_with_dot_pos(double i, unsigned int &pos)
{
std::stringstream ss;
ss << i;
std::string result(ss.str());
pos = 0;
while (pos < result.length() && result[pos] != '.') {
pos += 1;
}
return result;
}
int main(int argc, char **argv)
{
double d(12.54);
unsigned int pos(0);
// str should be "12.54".
// pos should be 2.
std::string str = to_str_with_dot_pos(d, pos);
std::cout << "double as string: " << str << std::endl;
std::cout << "double dot position: " << pos << std::endl;
return 0;
}
Explanation of the code (the while loop):
It gets every character of the std::string and checks if it does not equals to the . dot character, if the character is not equal to . it will add +1 to the pos variable.
It returns 2 and not 3 because we're counting from 0, not 1.
Also, this question is a duplicate.
Check that your version of MinGw support to_string, as the code above compiles correctly.
I'd recommend a different approach for length checking, one that avoids using strings:
#include <iostream>
#include <cmath>
using namespace std;
int is_len(int number, int len)
{
if(pow(10, len-1) <= number && number < pow(10, len))
return true;
return false;
}
int main()
{
int number = 1000;
cout << is_len(1, 2) << endl;
cout << is_len(1005, 4) << endl;
cout << is_len(9999, 4) << endl;
cout << is_len(599, 4) << endl;
cout << is_len(1005, 5) << endl;
return 0;
}
Prints:
0
1
1
0
0

Check each element of a string for a number or character

I am trying to make a program that tells the user to type a sentence or something.
Then i need to find how many numbers , characters , all others (symbols, periods, spaces etc...) are in the string.
Why will my code not work? I thing it has to do with the find_first_of checking the whole string at once while i want it to check only the index "i" position.
[Error] request for member 'find_first_of' in 's1.std::basic_string<_CharT, _Traits, _Alloc>::operator[], std::allocator >(((std::basic_string::size_type)i))', which is of non-class type 'char' is the error i get in the 2 commented lines of code below.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string s1;
int numbers = 0;
int characters = 0;
int others = 0;
cout << "Please type in Something: ";
getline(cin, s1);
cout << "You typed: " << s1 << endl;
for(int i = 0; i < sizeof(s1) / sizeof(string); ++i)
{
if(s1[i].find_first_of("123456789") != string::npos) // Here is where the compiler errors
{
++numbers;
}
else if(s1[i].find_first_of("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz") != string::npos) // And here with the same error
{
++characters;
}
else
{
++others;
}
}
cout << "Total numbers in the string are: " << numbers << endl << "Total characters in the string are: " << characters << endl << "Total special characters, symbols, spaces etc... are: "<< others;
return 0;
}
There are few problems with the code :
1.You can't invoke find_first_of on an character :
2.find_first_of won't help
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main ()
{
string s1;
int numbers = 0;
int characters = 0;
int others = 0;
cout << "Please type in Something: ";
getline(cin, s1);
cout << "You typed: " << s1 << endl;
for(size_t i = 0; i < s1.size(); ++i)
{
if(isdigit(s1[i])){++numbers;}
else if(isalpha(s1[i])){++characters;}
else{ ++others;}
}
cout << "Total numbers in the string are: " << numbers << endl
<< "Total characters in the string are: " << characters << endl
<< "Total special characters, symbols, spaces etc... are: "<< others<<endl;
return 0;
}
As to the error, s1[i] is a single character, it is not a std::string, so attempting to use it as a string object in the call to find_first_of will not work (doesn't compile).
Your code has at least two other issues:
Issue 1:
A std::string knows how many characters it has by calling its size() method. Therefore, this is wrong:
for(int i = 0; i < sizeof(s1) / sizeof(string); ++i)
It should be:
for(size_t i = 0; i < s1.size(); ++i)
Issue 2:
Usage of string::find_first_of is not necessary. There are functions that determine if a character is alpha and digit.
#include <cctype>
//...
if (std::isdigit(s1[i]))
++numbers;
else
if (std::isalpha(s1[i]))
++characters;
else
++others;
std::isdigit: http://en.cppreference.com/w/cpp/string/byte/isdigit
std::isalpha: http://en.cppreference.com/w/cpp/string/byte/isalpha