Insert a new line after each dot, C++ - c++

I have this code and I want to insert a new line after each dot with a insert statement. I get the error message no matching member function for call to 'insert'. What am I doing wrong?
#include<iostream>
#include<string>
using namespace std;
int main ()
{
string const inText1 = "I'm reading. ";
string const inText2 = "I like to read. ";
string const inText3 = "I'm gonna read that book. ";
string const inText4 = "She's reading. ";
string const inText5 = "He's reading. ";
string const inText6 = "READ. ";
string const inText7 = "Reading. ";
string inText8=inText1+inText2+inText3+inText4+inText5+inText6+inText7;
string::size_type dotpos = inText10.find(".");
if(dotpos != string::npos)
inText10.insert(dotpos, endl);
cout << inText10 << endl;
return 0;
}

Assuming inText10 is just inText8, this is the working code.
Changes done:
Earlier, the inText10 string was not found. So, insert() on that object might have produced your error.
The position to insert newline is NOT dotpos. Its dotpos + 1
Note this code just adds a newline after finding the first dot. To add newline after every dot, use while loop to find all dots and insert newline char next to it.
#include<iostream>
#include<string>
using namespace std;
int main ()
{
string const inText1 = "I'm reading. ";
string const inText2 = "I like to read. ";
string const inText3 = "I'm gonna read that book. ";
string const inText4 = "She's reading. ";
string const inText5 = "He's reading. ";
string const inText6 = "READ. ";
string const inText7 = "Reading. ";
string inText8=inText1+inText2+inText3+inText4+inText5+inText6+inText7;
string::size_type dotpos = inText8.find(".");
if(dotpos != string::npos)
inText8.insert(dotpos + 1, "\n");
cout << inText8 << endl;
return 0;
}

There are a lot of undefined variables in your code, but basically you receive 'no matching member function for call to 'insert'' because you are trying to insert std::endl into a string. std::endl can't be casted to char of any type, so, you can't do this.
To fix your issue, replace
inText10.insert(dotpos, endl);
with
inText10.insert(dotpos, '\n');
By the way, if you want to insert \n after every single dot, you should do find() in a loop, since find() returns a single matched char position, not an array.
To learn more, why you can't insert std::endl, read this std::endl description at cppreference

Related

The problem of analyzing a string and searching

I want to write code that takes a string of text from the user and shows the number of characters and the number of words using the .find () function. then takes a word from user and Search the text and show the position of the word. I'm in trouble now, please help me.
#include<iostream>
#include <cctype>
#include<string>
#include<cstring>
using namespace std;
int main()
{ char quit;
int word=0;
string txt;
cout << "Enter a string: ";
getline(cin, txt);
cout << "The number of characters in the string is:" << txt.length() << endl;
while(string txt != NULL)
{ if(txt.find(" "))
++word;
}
cout<<"wors is "<<word;
while(quit!='q')
{
cout<<"wors is ";
cin>>search;
cout<<"Enter(c)if you want to continue, and enter(q)if you want quic:";
cin>>quit;
}
return 0;
}
Here's an example of extracting words. There are many other methods.
static const char end_of_word_chars[] = "!?., :\t";
//...
std::string::size_type previous_position = 0;
std::string::size_type position = txt.find_first_of(end_of_word_chars);
while (position != std::string::npos)
{
std::string word = txt.substr(previous_position, position - previous_position);
std::cout << word << "\n";
previous_position = txt.find_first_of(position + 1);
position = txt.find_first_not_of(end_of_word_chars);
}
The above code uses an array of "end of word characters", to denote the end of a word. The string txt is searched from the beginning to find the position of the first character that is in the set of word endinging characters. In the while loop, the spaces or non-word characters are skipped. And the position of the next "word ending" character is found and the loop may repeat again.
Edit 1: String as stream
Another method is to treat the txt as a string stream and use operator>> to skip whitespace:
std::istringstream text_stream(txt);
std::string word;
while (text_stream >> word)
{
std::cout << word << "\n";
}
One issue with the above code fragment is that it doesn't account for word ending characters that are not spaces or tabs. So for example, in the text "Yes. I'm Home.", the period is included as part of the "word", such as "Yes." and "Home."

Capitalizing letters in C++

I have an assignment where the user enters a student name in the format ( last name, first name). Can you help me figure out how to capitalize the first letter for both the first name and the last name?
I was using this to turn the user input into an array, so I could have the first letter capitalized, but when I did this, I had trouble getting it to work outside of the for loop.
for (int x = 0; x < fName.length(); x++)
{
fName[x] = tolower(fName[x]);
}
fName[0] = toupper(fName[0]);
I used your code and just added some parsing around it. You really are very close.
I can't help myself. For user input, I always use getline() followed by a stringstream to parse the words from the line. I find it avoids a lot of edge cases that get me into quicksand.
When getline() gets an input, it returns true unless it has problems. If the user inputs Ctrl-d, it will return false. Ctrl-D is basically an EOF (end of file) code, which works well in this case (as long as you are not trying to input the Ctrl-d from inside your debugger. Mine does not like that.
Note that I am using std::string in place of an array. std::string can be treated like an array for subscripting, but it prints nicely and has other functions that make it better for processing character strings.
#include <iostream>
#include <string> // Allow you to use strings
#include <sstream>
int main(){
std::string input_line;
std::string fName;
std::string lName;
std::cout << "Please enter students as <lastname>, <firstname>\n"
"Press ctrl-D to exit\n";
while(std::getline(std::cin, input_line)){
std::istringstream ss(input_line);
ss >> lName;
// remove trailing comma. We could leave it in and all would work, but
// it just feels better to remove the comma and then add it back in
// on the output.
if(lName[lName.size() - 1] == ',')
lName = lName.substr(0, lName.size() - 1); // Substring without the comma
ss >> fName;
for (int x = 0; x < fName.length(); x++) // could start at x=1, but this works.
{
fName[x] = tolower(fName[x]); // make all chars lower case
}
fName[0] = toupper(fName[0]);
for (int x = 0; x < lName.length(); x++)
{
lName[x] = tolower(lName[x]);
}
lName[0] = toupper(lName[0]);
std::cout << "Student: " << lName << ", " << fName << std::endl;
}
}

Replacing word in position X of a string C++

I am trying to write a function in a program that will take a string, a word and an integer and use the int as the index value and the word as the replacement value. For example, if the string is "This is a test.", the word is "example", and the number is 4, then the result would be "This is an example". This is what I have so far (I had to make multiple copies of the string because eventually, I am going to be passing it into two other functions by reference instead of as value)Right now it is using the character index instead of the word index in order to replace. How do I fix that?
#include "pch.h"
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
string Input = "";
string Word = "";
int Number = 0;
cout << "Pleas enter a string using only lower case letters. \n";
getline(cin, Input);
cout << "Please enter a word using only lower case lettersS. \n";
getline(cin, Word);
cout << "Please enter a number. \n";
cin >> Number;
string StringCopy1 = Input;
string StringCopy2 = Input;
string StringCopy3 = Input;
}
void stringFunctionValue(string StringCopy1, int Number, string Word)
{
StringCopy1.replace(Number, Word.length, Word);
return StringCopy1;
}
First thing you have to do is find the nth word.
The first thing to come to mind is using std::istringstream to pull the string apart with >> and a std::ostringstream to write the new string.
std::istringstream in(StringCopy1);
std::string token;
std::ostringstream out;
int count = 0;
while (in >> token) // while we can get more tokens
{
if (++count != number) // not the number of the token to replace
{
out << token << " "; // write the token
}
else
{
out << word << " "; // write the replacement word
}
}
return out.str();
While this is easy to write, it has two problems: It loses the correct type of whitespace in the string AND places an extra space on the end of the string. It's also kind of slow and uses a lot more memory than if you modify the string in place.
Use std::string::find_first_not_of to find the first non-whitespace character. This will be the start of the first word. Then use std::string::find_first_of to find the next whitespace character. This will be the end of the word. Alternate back and forth finding non-whitespace then whitespace until you find the beginning and ending of the nth word. std::string::replace that word. This approach requires you to write more and more complicated code, but is much more satisfying. This is why I outlined it rather than fully implementing it: To allow you the joy for yourself.
Note: void stringFunctionValue(string StringCopy1, int Number, string Word) gives you no way to provide the result back to the user. This makes for an unhelpful function. Consider returning a string rather than void.

Finding pattern in a text in C++

I have written the following code to find the number of "ATA" in a text that is read to a string as "GCTATAATAGCCATA". The count returned should be 3 but it returns 0. When I check in debugger the string for text is initially created. However, when an empty string is passed to the function patternCount. Am I reading the contents of the file into the string text correctly?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void patternCount(string text, string pattern);
int main()
{
string text;
fstream file_("test.txt");
if(file_.is_open())
{
while(getline(file_,text))
{
cout << text << '\n';
}
file_.close();
}
cout << "Enter a string ";
string pattern;
getline(cin, pattern);
patternCount(text, pattern);
return 0;
}
void patternCount(string text, string pattern)
{
int count = 0;
size_t nPos = text.find(pattern, 0);
while (nPos != string::npos)
{
nPos = text.find(pattern, nPos + 1);
++count;
}
cout << "There are " << count <<" " << pattern << " in your text.\n";
}
This code just counts the number of occurrence of input string in the last line of text file. If that line is empty or no does not contain the string, The output result will be 0.
But I guess the OP wants to search a whole file, in which case the main function need be fixed accordingly.
std::ifstream file{"test.txt"};
std::ostringstream text;
std::copy(std::istream_iterator<char>{file}, std::istream_iterator<char>{},std::ostream_iterator<char>{text});
//...
patternCount(text.str(), pattern);
So if I understand correctly, you're not sure if you're reading correctly the contents from the file test.txt. If you want to read every content, then try this instead:
ifstream file_("test.txt");
string s,text;
file_>>s;
text=s;
while(file_>>s)
{
text=text+" "+s;
}
This should probably work. Note that reading from a file like filename>>string only reads till the first space. That's why I'm using the while. You can also use getline(), which reads the whole text with spaces. Also note that you should include fstream. Printing out the text should help more as well.
#include <iostream>
#include <fstream>
#include <string>
using std::cout;
using std::cerr;
using std::string;
int count = 0; // we will count the total pattern count here
void patternCount(string text, string pattern);
int main() {
cout << "Enter a string ";
string pattern;
std::getline(cin, pattern);
string text;
fstream file_("test.txt");
if(file_.is_open()){
while(std::getline(file_,text))
patternCount(text,pattern);
file_.close();
}else
cerr<<"Failed to open file";
cout << "There are " << count <<" " << pattern << " in your text.\n";
return 0;
}
void patternCount(string text, string pattern){
size_t nPos = text.find(pattern, 0);
while (nPos != string::npos) {
nPos = text.find(pattern, nPos + 1);
++count;
}
}
The Problem
Your code was good, there were no bugs in patternCount function.
But You were reading the file in an incorrect way. See, everytime you call std::getline(file_, text), the old result of the _text are overwritten by new line. So, in the end of the loop, when you pass text to patternCount function, your text only contains the last line of the file.
The Solution
You could have solved it in two ways:
As mentioned above, you could run patternCount() to each line in while loop and update a global count variable.
You could append all the lines to text in while loop and at last call the patternCount function.
Whichever you prefer, I have implemented the first, while second one is in other answers.

Count letters in String without using strlen()

I created a program that the user enters a string. But i need to count how many letters are in the string. The problem is im not allowed to use the strlen()function. So i found some methods but they use pointers but im not allowed to use that yet as we havent learned it. Whats the best way to do this in a simple method? I also tried chars but i dont have luck with that either.
#include <iostream>
using namespace std;
string long;
string short;
int main()
{
cout << "Enter long string";
cin >> long;
cout << "Enter short string";
cin >> short;
return 0;
}
I need to get the length of long and short and print it.
I am trying to use it without doing strlen as asked in some previous questions.
Do you mean something like this?
//random string given
int length = 1;
while(some_string[length - 1] != '\0')
length++;
Or if you don't want to count the \0 character:
int length = 0;
while(some_string[length] != '\0')
length++;
You can count from the beginning and see until you reach the end character \0.
std::string foo = "hello";
int length = 0;
while (foo[++length] != '\0');
std::cout << length;
If you use standard cpp string object I think the best way to get length of your string is to use method:
long.size();
It gives you number of characters in string without end string character '\0'. To use it you must include string library :
#include <string>
If you decide to use char table you can try method from cin:
char long_[20];
cout << "Enter long string\n";
int l = cin.getline(long_,20).gcount();
cout << l << endl;
gcount()