Question on combination of >>, << operators & cin and cout objects - c++

char word[10];
int n=5;
while(n--)
{
cin>>word;
cout<<n<<" "<<word<<" ";
}
Output:
ABC DEF GHI JKL MNO
4 ABC 3 DEF 2 GHI 1 JKL 0 MNO
Now, my question is what happens when input buffer encounters a blankspace(' ')? It is seen that n is being decremented after every white space but the cout << word does not display anything on screen.
I am confused as i think that the output should be displayed as soon as one word is input. Eg.
ABC 4 ABC DEF 3 DEF GHI 2 GHI JKL 1 JKL MNO 0 MNO

Not sure I understand your question, but if I'm reading you right: The stream extraction operator reads until it encounters whitespace, and then consumes the whitespace. You don't get a new word consisting of just the whitespace characters.
A few minutes later: I went back and re-read again, and now I think I understand what you're asking: the two streams are not synchronized, so the input and output can't be interleaved in the way you suggest.

cin read strings separated by space but space are discarded in the process

Try doing
cout << flush;
Or
cout << endl;
(inside the while)

Related

The cin.ignore removing first character the second time function is being called

Can anyone tell me what is wrong with this? Without cin.ignore, the getline would not work, and after the first time when I call the function again, the first character is removed. So far I have tried using stringstream instead of getline, cin.sync(), cin.clear(), but nothing seems to work. Also the reason why I am using getline, is because some streets have spaces between them, so simply using cin would not work in this case
std::cout << "Enter Street Name 1: " ;
std::cin.ignore(1,EOF);
std::getline(std::cin,s1);
std::cout << "Enter Street Name 2: " ;
std::getline(std::cin,s2);
std::cout<<"Your first street was: "<<s1<<" Your second street was: "<<s2 <<". Please look at the map to find the intersection of " << s1 << " and " << s2 <<std::endl;
Output
Enter Street Name 1: Bloor
Enter Street Name 2: Yonge
Your first street was: Bloor Your second street was: Yonge. Please look at the map to find the intersection of Bloor and Yonge
Enter Street Name 1: Bloor
Enter Street Name 2: Yonge
Your first street was: loor Your second street was: Yonge. Please look at the map to find the intersection of loor and Yonge
Enter Street Name 1: Bloor
Enter Street Name 2: Uong
Your first street was: loor Your second street was: Uong. Please look at the map to find the intersection of loor and Uong
Without cin.ignore, the getline would not work,
That is true only if there is some code before that that leaves a newline character in the input stream.
and after the first time when I call the function again, the first character is removed.
That makes sense. cin.ignore() reads and discards one character.
I am not able to suggest something that will fix your problem without a Minimal, Complete, and Verifiable Example.
because you use cin.ignore() without parameters which means ignore the next char in the buffer that's why the first character is removed. To use cin.ignore()
cin.ignore( int nCount = 1, int delim = EOF );
Parameters
nCount - The maximum number of characters to extract.
delim - The delimiter character (defaults to EOF).
example
std::cin.ignore(256,' '); // ignore until space

C++11 Regex search - Exclude empty submatches

From the following text I want to extract the number and the unit of measurement.
I have 2 possible cases:
This is some text 14.56 kg and some other text
or
This is some text kg 14.56 and some other text
I used | to match the both cases.
My problem is that it produces empty submatches, and thus giving me an incorrect number of matches.
This is my code:
std::smatch m;
std::string myString = "This is some text kg 14.56 and some other text";
const std::regex myRegex(
R"(([\d]{0,4}[\.,]*[\d]{1,6})\s+(kilograms?|kg|kilos?)|s+(kilograms?|kg|kilos?)(\s+[\d]{0,4}[\.,]*[\d]{1,6}))",
std::regex_constants::icase
);
if( std::regex_search(myString, m, myRegex) ){
std::cout << "Size: " << m.size() << endl;
for(int i=0; i<m.size(); i++)
std::cout << m[i].str() << std::endl;
}
else
std::cout << "Not found!\n";
OUTPUT:
Size: 5
kg 14.56
kg
14.56
I want an easy way to extract those 2 values, so my guess is that I want the following output:
WANTED OUTPUT:
Size: 3
kg 14.56
kg
14.56
This way I can always directly extract 2nd and 3th, but in this case I would also need to check which one is the number. I know how to do it with 2 separate searches, but I want to do it the right way, with a single search without using c++ to check if a submatch is an empty string.
Using this regex, you just need the contents of Group 1 and Group 2
((?:kilograms?|kilos?|kg)|(?:\d{0,4}(?:\.\d{1,6})))\s*((?:kilograms?|kilos?|kg)|(?:\d{0,4}(?:\.\d{1,6})))
Click for Demo
Explanation:
((?:kilograms?|kilos?|kg)|(?:\d{0,4}(?:\.\d{1,6})))
(?:kilograms?|kilos?|kg) - matches kilograms or kilogram or kilos or kilo or kg
| - OR
(?:\d{0,4}(?:\.\d{1,6})) - matches 0 to 4 digits followed by 1 to 6 digits of decimal part
\s* - matches 0+ whitespaces
You can try this out:
((?:(?<!\d)(\d{1,4}(?:[\.,]\d{1,6})?)\s+((?:kilogram|kilos|kg)))|(?:((?:kilogram|kilos|kg))\s+(\d{1,4}(?:[\.,]\d{1,6})?)))
As shown here: https://regex101.com/r/9O99Fz/3
USAGE -
As I've shown in the 'substitution' section, to reference the numeral part of the quantity, you have to write $2$5, and for the unit, write: $3$4
Explanation -
There are two capturing groups we could possibly need: the first one here (?:(?<!\d)(\d{1,4}(?:[\.,]\d{1,6})?)\s+((?:kilogram|kilos|kg))) is to match the number followed by the unit,
and the other (?:((?:kilogram|kilos|kg))\s+(\d{1,4}(?:[\.,]\d{1,6})?)) to match the unit followed by the number

Printing duplicate strings and how many times they appear in a file C++

Here is the question I have to solve and the code I've written so far.
Write a function named printDuplicates that accepts an input stream and an output stream as parameters.
The input stream represents a file containing a series of lines. Your function should examine each line looking for consecutive occurrences of the same token on the same line and print each duplicated token along how many times it appears consecutively.
Non-repeated tokens are not printed. Repetition across multiple lines (such as if a line ends with a given token and the next line starts with the same token) is not considered in this problem.
For example, if the input file contains the following text:
hello how how are you you you you
I I I am Jack's Jack's smirking smirking smirking smirking smirking revenge
bow wow wow yippee yippee yo yippee yippee yay yay yay
one fish two fish red fish blue fish
It's the Muppet Show, wakka wakka wakka
My expected result should be:
how*2 you*4
I*3 Jack's*2 smirking*5
wow*2 yippee*2 yippee*2 yay*3
\n
wakka*3
Here is my function:
1 void printDuplicates(istream& in, ostream& out)
2 {
3 string line; // Variable to store lines in
4 while(getline(in, line)) // While there are lines to get do the following
5 {
6 istringstream iss(line); // String stream initialized with line
7 string word; // Current word
8 string prevWord; // Previous word
9 int numWord = 1; // Starting index for # of a specific word
10 while(iss >> word) // Storing strings in word variable
11 {
12 if (word == prevWord) ++numWord; // If a word and the word 13 before it are equal add to word counter
14 else if (word != prevWord) // Else if the word and the word before it are not equal
15 {
16 if (numWord > 1) // And there are at leat two copies of that word
17 {
18 out << prevWord << "*" << numWord << " "; // Print out "word*occurrences"
19 }
20 numWord = 1; // Reset the num counter variable for next word
21 }
22 prevWord = word; // Set current word to previous word, loop begins again
23 }
24 out << endl; // Prints new line between each iteration of line loop
25 }
26 }
My result thus far is:
how*2
I*3 Jack's*2 smirking*5
wow*2 yippee*2 yippee*2
I have tried adding (|| iss.eof()), (|| iss.peek == EOF), etc inside the nested else if statement on Line 14, but I am unable to figure this guy out. I need some way of knowing I'm at the end of the line so my else if statement will be true and try to print the last word on the line.

c++ How to extract the whitespace between words if there is one

I've got two questions. I need to write a program that extracts all non-alphabetic characters and displays them, then removes them.
I am using isalpha which is working for symbols, but only if the input string has no spaces like "hello world"
but if it is more than one word like "hello! world!", it will only extract the first exclamation mark but not the second.
Second question which may be related, I want my program to detect the spaces between the words (I tried isspace but I must have used it wrong? and remove them and put them in a char variable
so for example
if the input is hello4 world! How3 are you today?
I want it to tell me
removed: 4
removed:
removed: !
removed:
removed: 3
removed:
removed:
removed:
long story short, if there is no other way, I'd like to detect spaces as !isalpha, or find something similar to isalpha for space between text.
Thanks
# include <iostream>
# include <string>
using namespace std;
void main()
{
string message;
cin >> message;
for (int i = 0; message[i]; i++)
if(!isalpha(message[i]))
cout << "deleted following character: " << message[i] <<endl;
else
cout <<"All is good! \n";
}
>> reads a single word, stopping when a whitespace character is found. To read a whole line, you want
std::getline(cout, message);
There is a better way by which you can get non-alphabetic characters,
You can check with asci value of each character and compare with alphabetic asci character if not in it & not a space (space asci val),
then you get your non-alphabetic character.
You can get all ascii codes over here :=> http://www.asciitable.com/
-Jayesh

How to make my function only find real worlds from permutation

The code below gets a word from the user and then switches each letter around, it list all the possible combinations that it can make, I wish to filter out all the results that aren't words, I have a dictionary and words from the dictionary can get grabbed using GetWord();
an example
input admirer
output married
currently it would do
input admirer
output admirre, adminerr...ect
The following code makes this happen.
void Permutations(string input) {
//sorts input for new word
sort(input.begin(), input.end());
do cout << input << endl; while (next_permutation(input.begin(), input.end()));
}
int FindPermutations() {
string word;
cout << "Input word: ";
cin >> word;
//Runs Premutations with given string
Permutations(word);
return 0;
}
So my question is how can I make the permutation only find real words?
Download an English dictionary text file from http://wordlist.sourceforge.net.
Or if you are on unix: cat /usr/share/dict/words > words.txt
Check if the word exists in the file to figure if its a real word.
You could use a look up table containing the starting location of the first word of each alphabet in the file and jump to that location to optimise the search algorithm a little.