I'm just learning c++. I have a problem with my program. I have to write a program which reverse string and count amount word in the string. My program doesn't return amount words and reverse only last word in string. I totally don't know how to correct it. :D
#include <iostream>
using namespace std;
void reverseString(string str)
{
for (int i=str.length()-1; i>=0; i--)
{
cout << str[i];
}
}
void countString(string strg)
{
int word = 1;
for(int j = 0; strg[j] != '\0'; j++)
{
if (strg[j] == ' ')
{
word++;
}
}
}
int main(void)
{
string inputString;
cout << "Give a string: ";
cin >> inputString;
cout << "Reverse string: ";
reverseString(inputString);
cout << "\nCounts words in a string: ";
countString(inputString);
return 0;
}
If you want to read multiple words then you must use getline as >> reads only a single word.
string inputString;
cout << "Give a string: ";
getline(cin, inputString);
To return something from a function you must 1) specify the return type and 2) use a return statement to return a value and 3) do something with that return value in the calling function
Step 1
int countString(string strg) // here we say countString returns an integer
{
...
}
Step 2
int countString(string strg)
{
...
return words; // here we say the value we want to return
}
Step 3
// here we output the value returned from the function
cout << "\nCounts words in a string: " << countString(inputString) << "\n";
Knowing how to write functions that return values is absolutely fundamental C++. You should practise this. See if you can do the same with your reverseString function, instead of printing a string make it return a string.
There are some mistake in your code.In countString() function you return nothing.So it does not print anything.If you take input as a string include a space character,please use getline(cin, inputString).Here the code for you:
#include <iostream>
using namespace std;
void reverseString(string str)
{
for (int i=str.length()-1; i>=0; i--)
{
cout << str[i];
}
}
int countString(string strg)
{
int word = 0;
for(int j = 0; strg[j] != '\0'; j++)
{
word++;
}
return word;
}
int main(void)
{
string inputString;
cout << "Give a string: ";
getline(cin, inputString);
cout << "Reverse string: ";
reverseString(inputString);
cout << "\nCounts words in a string: ";
cout<<countString(inputString)<<endl;
return 0;
}
Related
This code should say if a word is present in a sentence or not. When I insert the sentence and the word where I declare the strings(for exemple: string s = "the cat is on the table" string p = "table" the program says that the word is in the sentence) the code works but, with the getline, the for cycle never begin and it always says that the word isn't in the sentence.
Please help I dont know what to do
#include <iostream>
#include <string>
using namespace std;
int main () {
string s;
string p;
string word;
bool found = false;
int sl = s.length();
int beg = 0;
int pl = p.length();
cout << "sentence: ";
getline(cin, s);
cout << "word: ";
getline(cin, p);
for(int a = 0; a<sl; a++)
{
if(s[a]== ' ')
{
word = s.substr(beg, a-beg);
if (word== p)
{
found = true;
break;
}
beg = a+1;
}
}
if (found== true)
{
cout <<"word " << p << " is in a sentence " << s;
}
else
{
word = s.substr(beg);
if (word== p)
{
found = true;
}
if(found == true)
{
cout <<"the word " << p << " is in the sentence " << s;
}
else
{
cout <<"the word " << p << " isn't in the sentence " << s;
}
}
}
after taking the input strings then use length() to find the length, otherwise you are not taking the actual size of the strings.
getline(cin, s);
getline(cin, p);
int sl = s.length();
int pl = p.length();
For splitting the words after taking the input string by getline() you can use stringstream which is a builtin c++ function, like :
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string arr;
getline(cin, arr);
stringstream ss(arr);
string word;
while(ss >> word){
// your desired strings are in `word` one by one
cout << word << "\n";
}
}
Another thing is that you can declare the strings like string s, p, word;
I have attempted to remove the occurrences of a user inputted letter after they've chosen a word however, the final output prints out a random string of letters and numbers instead of what I expected. For example, if the user enters the text "Coffee" then proceeds to enter the letter "f", the program should return "Coee" as the final print. However, this is not the case. Could anyone check to see where I've gone wrong? Much obliged.
#include <iostream>
#include <string>
using namespace std;
void removeAllOccurrence(char text[], char letter)
{
int off;
int i;
i = off = 0;
if (text[i] == letter)
{
off++;
}
text[i] = text[i + off];
}
int main() {
string text;
char letter;
string newText;
cout << "Type your text: " << endl;
cin >> text;
cout << "Choose the letters to remove: " << endl;
cin >> letter;
cout << "your new text is: " << removeAllOccurrence << endl;
system("pause");
return 0;
}
This should do the job
#include <algorithm>
#include <string>
#include <iostream>
void remove_char(std::string s, char r) {
s.erase( std::remove( s.begin(), s.end(), r), s.end()) ;
std::cout << s << std::endl;
}
int main()
{
std::string test = "coffee";
char r = 'f';
remove_char(test, r);
return 0;
}
If u want to do this by hand try this:
std::string removeAllOccurrence(string text, char letter)
{
int off;
int i;
i = off = 0;
string out = "";
for (i = 0; i < text.size(); i++)
{
if (text[i] != letter)
{
out += text[i];
}
}
return out;
}
int main(void)
{
string text;
char letter;
string newText;
cout << "Type your text: " << endl;
cin >> text;
cout << "Choose the letters to remove: " << endl;
cin >> letter;
cout << "your new text is: " + removeAllOccurrence(text, letter) << endl;
system("pause");
return 0;
}
As you can see your main function was kinda right. You just need to pass some arguments into the function. Additonally you missed a loop in your remove function. If you use string in your main, why don't use string in yur function? You can just use string there, too
Kind Regards
How do I read the new line character? I am trying to do a character count, but the new line gets in the way. I tried doing if (text[i] == ' ' && text[i] == '\n') but that didn't work. Here is my repl.it session.
I am trying to read this from file.txt:
i like cats
dogs are also cool
so are orangutans
This is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream input;
input.open("file.txt");
int numOfWords = 0;
while (true)
{
string text;
getline(input, text);
for(int i = 0; i < text.length(); i++)
{
if (text[i] == ' ')
{
numOfWords++;
}
}
if (input.fail())
{
break;
}
}
cout << "Number of words: " << numOfWords+1 << endl;
input.close();
}
Your question is asking how to count characters, but your code is counting words instead. std::getline() swallows line breaks. You don't need to worry about them if you want to count words. In fact, you can use operator>> to greatly simplify your counting in that case, eg:
int main()
{
ifstream input("file.txt");
int numOfWords = 0;
string word;
while (input >> word)
++numOfWords;
cout << "Number of words: " << numOfWords << endl;
return 0;
}
If you really want to count characters instead of words, use std::ifstream::get() to read the file 1 character at a time, eg:
int main()
{
ifstream input("file.txt");
int numOfChars = 0;
int numOfWords = 0;
bool isInSpace = true;
char ch;
while (input.get(ch))
{
++numOfChars;
if (std::isspace(ch, input.getloc())) {
isInSpace = true;
}
else if (isInSpace) {
isInSpace = false;
++numOfWords;
}
}
cout << "Number of chars: " << numOfChars << endl;
cout << "Number of words: " << numOfWords << endl;
return 0;
}
The loop in the program seems to execute at least once, even if there are no occurences of the substring. Why is this?
#include <iostream>
#include <string>
using namespace std;
int countSubstrings(const string& original_string, const string& substr) {
int number_of_ocurrences = 0;
int i = 0;
for (i = original_string.find(original_string, 0); i != string::npos;
i = original_string.find(substr, i)) {
number_of_ocurrences++;
i++;
}
return number_of_ocurrences;
}
int main() {
string input;
while (1) {
cout << "Enter a a line of text: ";
getline(cin, input, '\n');
cout << '\n';
cout << "Number of ocurrences of the word needle: ";
cout << countSubstrings(input, "needle") << '\n';
}
}
Initially when you set i in your for loop you have
original_string.find(original_string, 0)
So you are searching the string for itself which it will find. I believe you meant to have
original_string.find(substr, 0)
I'm a C++ newbie, I'm trying to put in practice pointers with strings. The program I have made is just to store strings the user types in the command line. But I'm getting segfault, not sure why.
This is the code:
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
//This code is meant to learn how to use pointers and strings
//Ask the user for who are they in the family and save it in string array!
void print_string (string* Value, int const nSize);
int get_names(string* Family_input);
int main ( int nNumberofArgs, char* pszArgs[])
{
cout << "Tis program stores your family members\n";
cout<< "Type the names and write 0 to exit\n";
string familia_string;
string* familia = &familia_string;
int family_number;
family_number=get_names(familia);
cout << "The family members are: ";
print_string(familia, family_number);
cout << endl;
return 0;
}
int get_names(string* Family_input)
{
int i=0;
string input="";
string old_input="";
while (input!="0")
{
cout << "type " << i <<" member\n";
//cin >> *(Family_input+i);
//input=*(Family_input+i);
cin >> input;
*(Family_input + old_input.length()) = input;
old_input=input;
i++;
}
return i;
}
void print_string (string* Value, int const nSize)
{// I don't want to &psValue to be changed!
for (int i=0; i<nSize; i++)
{
cout << *(Value+i) << " ";
//&psValue++;
}
}
I'm not sure if it's because I'm not taking correctly the size of the string, or I'm not using correctly the pointer or is that I have to allocate memory before using the offset.
As #kleszcz pointed out already, the line
*(Family_input + old_input.length()) = input;
is wrong. You are accessing memory that you are not supposed to.
The easiest fix is to change get_names slightly:
int get_names(string* Family_input)
{
int i=0;
string input="";
while (input!="0")
{
cout << "type " << i <<" member\n";
cin >> input;
*Family_input += input; // Just keep on appending to the input argument.
*Family_input += "\n"; // Add a newline to separate the inputs.
i++;
}
return i;
}
Also change print_string to:
void print_string (string* Value)
{
cout << *Value;
}
Of course, print_string has become so simple, you don't need to have it at all.
You could change get_names to use a reference argument instead of a pointer argument. This is a better practice.
int get_names(string& Family_input)
{
int i=0;
string input="";
while (input!="0")
{
cout << "type " << i <<" member\n";
cin >> input;
Family_input += input; // Just keep on appending to the input argument.
Family_input += "\n"; // Add a newline to separate the inputs.
i++;
}
return i;
}
Then, change the call to get_names. Instead of using
family_number=get_names(familia);
use
family_number=get_names(familia_string);
You get seg fault because you haven't allocate memory for an array of strings.
*(Family_input + old_input.length()) = input;
This is total nonsense. If you'd have an array you increment index only by one not by length of string.
If you want to save different names in different string objects I would suggest:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void print_string(string** Value, int const nSize);
void get_names(string** Family_input, int count);
int main(int nNumberofArgs, char* pszArgs[]) {
cout << "This program stores your family members\n";
int family_number;
cout << "Types the number of family members";
cin >> family_number;
/*allocate the number of string pointers that you need*/
string** familia = new string*[family_number];
cout << "Type the names\n";
get_names(familia, family_number);
cout << "The family members are: ";
print_string(familia, family_number);
cout << endl;
return 0;
}
void get_names(string** Family_input, int count) {
for(int i = 0 ; i < count; i++){
cout << "type " << i << " member\n";
/*create a string obj in the heap memory*/
string *input = new string ("");
// using that way you get only a single word
cin >> *input;
/*create a string object on the stack and put its pointer in the family_array*/
Family_input[i] = input;
}
}
void print_string(string** Value, int const nSize) {
for (int i = 0; i < nSize; i++) {
cout << *(Value[i]) << " ";
}
}