Input terminal problems and map - c++

I am using map to count the occurence of words. Here is the code.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string,int>wordcount;
string s;
while (cin>> s && s!="red")
++wordcount[s];
while (cin>>s && s!="red")
cout << s << " " << wordcount[s] << endl;
return 0;
}
I start the program, type words and at the last line enter the word "red", but it does not do anything. Then I type "red" the second time and it outputs:
press any key to continue
what is wrong?

Nothing is wrong. Visual Studio will automatically PAUSE the program before it ends to prevent the console window from closing, when you "Run without Debugging".

I understand that you want to receive a list of words, fill each word's number of occurrences into a map, and print it.
So, instead of the second while loop, you need to iterate on the map that you created and print the count for each word.
You can learn here how to print the map's contents.

Too groggy to write here, but I'll try a second time. :)
If you write a lot of words, it will count them up until you write "red".
The second loop will print the count for the words you input, but if you put "red" right away it will simply terminate the program without printing anything.
Try running the program with the following input:
one
two
two
red
zero
one
two
red

Related

Filling a cstring using <cstring> with text from a textfile using File I/O C++

I began learning strings yesterday and wanted to manipulate it around by filling it with a text from a text file. However, upon filling it the cstring array only prints out the last word of the text file. I am a complete beginner, so I hope you can keep this beginner friendly. The lines I want to print from the file are:
"Hello World from UAE" - First line
"I like to program" - Second line
Now I did look around and eventually found a way and that is to use std::skipary or something like that but that did not print it the way I had envisioned, it prints letter by letter and skips each line in doing so.
here is my code:
#include <fstream>
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int main() {
ifstream myfile;
myfile.open("output.txt");
int vowels = 0, spaces = 0, upper = 0, lower = 0;
//check for error
if (myfile.fail()) {
cout << "Error opening file: ";
exit(1);
}
char statement[100];
while (!myfile.eof()) {
myfile >> statement;
}
for (int i = 0; i < 30; ++i) {
cout << statement << " ";
}
I'm not exactly sure what you try to do with output.txt's contents, but a clean way to read through a file's contents using C++ Strings goes like this:
if (std::ifstream in("output.txt"); in.good()) {
for (std::string line; std::getline(in, line); ) {
// do something with line
std::cout << line << '\n';
}
}
You wouldn't want to use char[] for that, in fact raw char arrays are hardly ever useful in modern C++.
Also - As you can see, it's much more concise to check if the stream is good than checking for std::ifstream::fail() and std::ifstream::eof(). Be optimistic! :)
Whenever you encounter output issues - either wrong or no output, the best practise is to add print (cout) statements wherever data change is occurring.
So I first modified your code as follows:
while (!myfile.eof()) {
myfile >> statement;
std::cout<<statement;
}
This way, the output I got was - all lines are printed but the last line gets printed twice.
So,
We understood that data is being read correctly and stored in statement.
This raises 2 questions. One is your question, other is why last line is printed twice.
To answer your question exactly, in every loop iteration, you're reading the text completely into statement. You're overwriting existing value. So whatever value you read last is only stored.
Once you fix that, you might come across the second question. It's very common and I myself came across that issue long back. So I'm gonna answer that as well.
Let's say your file has 3 lines:
line1
line2
line3
Initially your file control (pointer) is at the beginning, exactly where line 1 starts. After iterations when it comes to line3, we know it's last line as we input the data. But the loop control doesn't know that. For all it knows, there could be a million more lines. Only after it enters the loop condition THE NEXT TIME will it come to know that the file has ended. So the final value will be printed twice.

getch() reads two characters from one arrow key press

Today i was testing how key pressing might work in C++ and made simple loop for it,and found that getch() duplicate itself for some reason or idk what is going on honestly,just look at that:
#include <iostream>
#include <windows.h>
#include <conio.h>
#define VK_H 0x48
using namespace std;
int main()
{
int n=1;
int total=0;
bool theEnd=true;
while(theEnd)
{
cout<<total<<endl;
getch();
if(GetAsyncKeyState(VK_LEFT))
{
total -=n;
}else if(GetAsyncKeyState(VK_RIGHT))
{
total +=n;
}else if(GetAsyncKeyState(VK_LSHIFT) && GetAsyncKeyState(VK_F1))
{
total = 0;
} else if(GetAsyncKeyState(VK_ESCAPE))
{
break;
}
}
cout<<total<<endl;
}
Its pretty simple.Program starts with a loop,where endlessly outputs value of variable "total",and after pressing left/right buttons "total" decrements/increments by 1.
Its was worked fine and perfect when i was using system("pause"); Sleep(milliseconds); cin.get();(but this one assume pressing enter each time,so it is not proper one) ,all that output right value on the screen after each pressing on the buttons.But in case with getch(); it somehow appear to working like only one time per/two cycles of the loop.
So the result i've get is like this: i'm pressing button right - current loop working fine,but next one working like without getch(),incrementing and outputting one more time without my command...
I've siting and thinking couple hours,trying find any answers in google and here but nothing...
P.S.without using getch() or other things for purpose stoping loop till next pressing - it will add not +1 to total by single pressing(as i need),but hundreds(average pressing key will do 150-300 loops lol).
From MS documentation
Remarks
The _getch and_getwch functions read a single character from the
console without echoing the character. None of these functions can be
used to read CTRL+C. When reading a function key or an arrow key, each
function must be called twice; the first call returns 0 or 0xE0, and
the second call returns the actual key code.
When you press arrow keys, the input is 2 chars

What is the purpose of using cin.get() in a while loop?

I don't understand why I have to use cin.get() again in while loop. Using cin.get() prior to the while loop does the same thing that cin.get() would do while also in the while loop. It reads a string of text I input while accounting for spaces. But obviously in this program I am trying to push all the text into a vector. If I were to exclude the cin.get(next) from the while loop and only have the line.push_back(next), then the program gets an error and crashes.
Please explain why it does this. Thank you
//Demonstration of the generic find function
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
vector<char> line;
cout << "Enter a line of text: \n";
char next;
cin.get(next);
while(next != '\n')
{
line.push_back(next);
cin.get(next);
}
return 0;
}
Here´s a little guide to help you out. Sometimes it´s hard to see the forest for the trees at the beginning.
Define a variable named next of type char
char next;
Since next has no meaningful value right now, let´s get one. We need it for the condition in our while statement.
cin.get(next);
Lets loop around till next equals '\n'
while(next != '\n')
{
We still did not do anything meaningful with next the only thing we know is that it doesn´t equal '\n' so we really ought to do something with it.
We push it in our vector.
line.push_back(next);
great. Done so far. We now need a new value for next for several reasons. On the one hand if we don´t change next we will loop forever (or too long at least) since the condition of the loop won´t get something new to chew on and on the other hand we want a new value for our vector, don´t we?
So yes, lets get the next next
cin.get(next);
And back to the beginning of our loop for testing
}
that´s it.

boost split - cout and vector - explain behaviour of this

I'm quite new to c++ and boost, I don't understand what's actually happening here.
So I'm using cin to get some input from the user. Then I'm splitting that string of spaces into a vector and trying to print the first index of the vector.
My code:
std::string cmd;
std::vector<std::string> args;
while (std::cin >> cmd) {
boost::split(args, cmd, boost::is_any_of(" "), boost::token_compress_on);
Console::print(args[0]);
break;
//reset the vector
//std::cin.clear();
//args.clear();
}
My console print function just uses normal cout, here is the code for it:
int Console::print(std::string message, int color)
{
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(consoleHandle, brightGreen);
std::cout << "myconsole :: ";
SetConsoleTextAttribute(consoleHandle, color);
std::cout << message << "\n";
return 0;
}
What's happening:
For the sake of this question the input is "start go".
I only want to print the first element. Without the break my program first prints start and then it prints out go. I have determined that the program does 2 loops and each time prints the first element, I know this because if I have the break then there is only start printed and the program ends. Firstly, why is this happening? Why does the first index of the vector get removed and then looped making the first index "go"?
Does this all have something to do with the stringstream/buffer or something. I don't know much about these. That was my guess so I tried to reset the buffer with cin.clear() and empty the vector with args.clear() but that still produced the same results.
Secondly, if I use the code below and try to access the 2nd element "go" my program just crashes. From what I have tried from the above I can assume that I am correctly splitting the string.
Is there some sort of asynchronous behavior going on and the split function just isn't finished yet? Or?
Any help would be awesome. Thanks.
Your problem is that std::cin >> cmd only reads "start", feeds that into the loop (which creates a single element vector and prints the only element), then loops round and does the same with "go".
You need while(std::getline(std::cin, cmd)).
You also need to learn to use your debugger which would have shown you what the problem was.

Read from certain coordinates?

Is there a way thorough which I can see what character occupies a certain coordinate. Let's say I have the following output:
Hello World !
I want to able to to see the x character on the y line. Something like:
readCoordinates(0,3);
This function should return 'l' , because the 4th character (because I started counting from 0) from the 1st line is 'l'. Can I do this type of readings in C++ from an already printed string ?
You might consider defining your own custom print function, which logs in a vector everything you've already outputted to the console. That way, you could easily grab a character, or string, from the console.
It might take up a lot of memory, however, if you're outputting thousands of lines.
You could do this from the string that is printed, but after it is printed it is just pixels on a screen, or ink on a printer. So, the answer is no, unless you have e.g. a vision system to look around and see where it was printed, recognize the letters and lines, and figure out the coordinates.
"Can I do this type of readings in C++ from an already printed string ?"
Good approach would be to store output of your program in memory so that your function readCoordinates could access random character in O(1). I would definitely use std::vector<std::string> outputBuffer which would allow you something like this: outputBuffer[0][3].
Example:
#include <iostream>
#include <vector>
#include <string>
std::vector<std::string> outputBuffer;
char readCoordinates(int line, int character)
{
if (line < outputBuffer.size() && character < outputBuffer[line].size())
return outputBuffer[line][character];
return 0;
}
int main()
{
std::string myOutput("Hello World !");
outputBuffer.push_back(myOutput);
std::cout << myOutput << std::endl;
if (char c = readCoordinates(0, 3))
std::cout << c << std::endl;
}
output:
Hello World !
l