Building a list of words from a sentence inputted - c++

I am fairly new to programming and would like help with my homework. I have no idea where to even start.
"
1. Have the user input a sentence
2. Print out the individual words in the sentence, along with the word number
So the string "This is a test of our program." should produce:
1. This
2. is
3. a
4. test
5. of
6. our
7. program
This should strip out all spaces, commas, periods, exclamation points."
if you can give me some pointers. thanks.

You will have to use strings and streams from the standard library. You can start by including the following headers
#include <string>
#include <iostream>
A good starting point would be to look at the introduction here
Try some stuff with std::cout. This method allows you to output content to the console. Start with something easy, such as:
std::cout << "Hello World" << endl;
You can also output the content of a variable the same way:
std::string myString = "SomeText";
std::cout << myString << endl;
std::cout does the opposite. It allows you to capture the user input into a variable.
int myNumber;
std::cin >> myNumber;
or
std::string userInputString;
std::getline(std::cin, userInputString)
Notice that in the second case we're using std::getline. This is because std::cin behaves in such a way that it will stop after the first word if you write an entire sentence.
Now that you've captured the user input string, you can remove undesired characters, split the string, etc.. Look at what is available in the string class. Good luck.

Related

How to remove duplicate phrases that are separated by being inside double quotes or separated by a comma in a file with c++

I use this function to remove duplicate words in a file
But I need it to remove duplicate expressions instead
for example What the function is currently doing
If I have the expression
"Hello World"
"beautiful world"
The function will remove the word "world" from both expressions
And I need this function to replace the entire expression only if it is found more than once in the file
for example
If I have the expressions
"Hello World"
"Hello World"
"beautiful world"
"beautiful world"
The function will remove the expression "Hello world" and "beautiful world" and leave only one from each of them but it will not touch the word "world" because the function will treat everything that is within the quotes as one word
This is the code I use now
#include <string>
#include <sstream>
#include <iostream>
#include <unordered_set>
void Remove_Duplicate_Words(string str)
{
ofstream Write_to_file{ "test.txt" };
// Used to split string around spaces.
istringstream ss(str);
// To store individual visited words
unordered_set<string> hsh;
// Traverse through all words
do
{
string word;
ss >> word;
// If current word is not seen before.
while (hsh.find(word) == hsh.end()) {
cout << word << '\n';
Write_to_file << word << endl; // write to outfile
hsh.insert(word);
}
} while (ss);
}
int main()
{
ifstream Read_from_file{ "test.txt" };
string file_content{ ist {Read_from_file}, ist{} };
Remove_Duplicate_Words(file_content);
return 0;
}
How do I remove duplicate expressions instead of duplicate words?
Unfortunately my knowledge on this subject is very basic and usually what I do is try all kinds of things until I succeed. I tried to do it here too and I just can not figure out how to do it
Any help would be greatly appreciated
Requires a little bit of String parsing.
Your example works by reading tokens, which are similar to words (but not exactly). For your problem, the token becomes word OR quoted string. The more complex your definition of tokens, the harder the problem becomes. Try starting by thinking of tokens as either words or quoted strings on the same line. A quoted string across lines might be a little more complex.
Here's a similar SO question to get you started: Reading quoted string in c++. You need to do something similar, but instead of having set positions, your quoted string can occur anywhere in the line. So you read tokens something like this:
Read next word token (as you're doing now)
If last read token is quote character ("), read till next (") as a single token
Check on the set and output token only if it isn't already there (if token is quoted, don't forget to output the quotes)
Insert token into set.
Repeat till EOF
Hope that helps

Reading In Formatted Data with Multiple Delimiters C++

I'm trying to read in data from command prompt with multiple delimiters, for example:
data 1, data2, data3.
I'd like the code to read in the data before the first comma, the data after that and before the second comma, and finally the data after that but before the period. I have been using this:
getline(cin, VAR, ',');
cin.get();
getline(cin, VAR2, ' ');
getline(cin, VAR3, ',');
cin.get();
getline(cin, VAR4, '.');
And it does what I want, provided the information is entered correctly. However, how can I check and see if the information wasn't? Because if the user doesn't enter two commas and a period, the program gets stuck as I'm assuming the cin stream gets broken after not finding the delimiter as specified in the getline() read. I've tried this:
if (cin.fail()) {
cout << "failure" << endl;
}
After a getline, but it never runs if the delimiter isn't input. What's the best way to do this, check for errors and see if data wasn't entered in the desired format?
You have to parse the input yourself.
For starters, your input does not consist of "data with multiple delimiters". Your input consists of a single line of text, that was entered, according to your description, at a command prompt of some kind.
If so, then the line of text should be read with a single std::getline() library function, since, by default, std::getline() uses \n as a default delimiter.
std::string str;
std::getline(std::cin, str);
Now, you've read your input into str. Now that this task is complete you can get down to business verifying whether str contains properly formatted input with the appropriate delimiters, or not.
To do that, you will use the rich set of methods that are available from your std::string object. For example one such method, find(), searches the string for a particular character, such as your first comma:
auto n=str.find(',');
The full documentation for find(), whose description you will find in your C++ book, will explain how to determine whether find() actually found the comma, or not. Based on that your program can either take the appropriate action (if the comma was not found) or use the substr() method, on this str, to extract the part of the string before the comma. That would be your first VAR. Then, use substr() again to extract the rest of the entered text, after the first comma.
You will also find a complete description of substr() in your C++ book.
After using substr() to extract the rest of the entered text, after the first comma, you will simply repeat the same overall process for extracting data2, and the following item of input, this time using a period.
And, at each step of the way you will have all the information your program will need to determine whether or not your input was formatted correctly.
You could read in the entire line into a std::string, then use std::istringstream to parse the string:
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
int main(void)
{
const std::string input_text = "data1, data2, data3\n";
std::istringstream input_stream(input_text);
std::string data1;
std::string data2;
std::string data3;
std::getline(input_stream, data1, ',');
std::getline(input_stream, data2, ',');
std::getline(input_stream, data3, ',');
std::cout << "data1: " << data1 << '\n';
std::cout << "data2: " << data2 << '\n';
std::cout << "data3: " << data3 << '\n';
return EXIT_SUCCESS;
}
If the std::getline fails, that means there is an error in the data.

String stream output compare

I want to compare output of stringstream with some string.
Problem is when I use fill and width on stringstream I cant compare resulting string with preloaded string.
std::stringstream sstr;
sstr.fill(' ');
sstr.width(4);
sstr << 4 << std::endl;
if(" 4" == sstr.str()){
std::cout << "Equal" << std::endl;
}
It's not equal. My educated guess would be that width somehow use some kind of flag or other kind of indicator to replace bunch of spaces in string. But I am not sure and didn't find anything useful on google. Does anyone know why I cannot compare that (sstream.str() and targeted string)?
Goal is to test what will stringstream (which is heart of my component) print on console.
You also inserted a std::endl into the string. That's going to add a newline character to the string.
Remove the std::endl from your output.

How do I make a string vector keep spaces from user input?

I do apologize if this has been asked before, but I haven't really seen this come up in my books or in other examples. So here I go.
I have been getting into a card game, after getting lazy with constant shuffling I made a program that does it for me, theoretically. I realize there are already programs that do so, but where is the fun in that? Onto the problem that led to the question. Whenever I typed in a card with a two or more word name, it chopped off all the words but the first. I have known this to happen but I don't know how to fix it normally. Let alone how to store "A, the C" in a vector and keep spaces.
The Question: How do I store a string like "A, the C" in a string and put it in a container and be able to retrieve it with the spaces in tact? Am I doing something wrong in the code, or am I using the wrong tool for the shed?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string example = " ";
cin >> example; //typed eggs and milk, only got eggs
cout << example << endl;
}
Instead of
cin >> example;
use
std::getline(std::cin, example);
cin >> example; will stop reading when it finds a white space. std::getline will cotinue reading until a specified delimiter ('\n' by default) is found.
More on std::getline.

c++ change space to enter

I don't know if this is even possible.
I have an assignment to translate words and phrases into pig Latin in C++. the fastest way to do this would be to have the user hit enter after each word, but this would make entering a continuous phrase impossible without hitting enter instead of the space bar.
your
text
would
be
entered
like
this
The your output could easily be:
youway exttay ouldway ebay enteredway ikelay histay
But still putting the info in would be weird.
Instead I would like to force the program to treat the space bar as though it were the enter key (carriage return).
your text would be entered like this
That way each word would enter my array separately from the string, the user only having to hit enter 1 time.
You could do something like:
Read a line of text from user input (which may have multiple words)
Split the line into words
Translate each word into Pig Latin
Print the words out with spaces between them
Rather than thinking of this in terms of "how can I change these keys to mean something else", think of it in terms of "how can I best work with what the user is expecting to type". If the user is expecting to type spaces between words (makes sense), then design your program so that it can handle that kind of input.
You can have the user input data as a single line, since that seems natural.
If you want some help in parsing the words to operate on the one at a time, then try this other question.
Here's the cheap-o way to do it:
std::string in;
while (std::cin >> in)
std::cout << piglatin(in) << char(std::cin.get());
std::cin >> in skips any leading whitespace in the input stream, and then fills in with the next whitespace-terminated word from the input stream, leaving the whitespace termination in the input stream. char(std::cin.get()) then extracts that terminator (which might be a space or a new line). The while loop is terminated by an end-of-file.
You can use that provided you understand it.
Added:
Here's a better way to find whether the word read was terminated with a space or a new-line:
#include <cctype>
char look_for_nl(std::istream& is) {
for (char d = is.get(); is; d = is.get()) {
if (d == '\n') return d;
if (!isspace(d)) {
is.putback(d);
return ' ';
}
}
// We got an eof and there was no NL character. We'll pretend we saw one
return '\n';
}
Now the hack looks like this:
std::string in;
while (std::cin >> in)
std::cout << piglatin(in) << look_for_nl(std::cin);