Read from certain coordinates? - c++

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

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.

Space vs null character

In C++, when we need to print a single space, we may do the following:
cout << ' ';
Or we can even use a converted ASCII code for space:
cout << static_cast<char>(32); //ASCII code 32 maps to a single space
I realized that, printing a null character will also cause a single space to be printed.
cout << static_cast<char>(0); //ASCII code 0 maps to a null character
So my question is: Is it universal to all C++ compilers that when I print static_cast<char>(0), it will always appear as a single space in the display?
If it is universal, does it applies to text files when I use file output stream?
No, it will be a zero(0) character in every compiler. Seems that the font you use renders zero characters as a space. For example, in the old times, DOS had a different image (an almost filled rectangle) for zero characters.
Anyway, you really should not output zero characters instead of spaces!
As for the text file part: open the outputted file using a hex editor to see the actual bits written. You will see the difference there!
On my computer, this code
#include <iostream>
int main() {
std::cout << "Hello" << static_cast<char>(0) << "world\n";
}
outputs this:
Helloworld
So no, it clearly doesn’t work.

Why it works when I type multiple characters in a character variable?

I am a new C++ user.
My code is as following:
#include <iostream>
using namespace std;
int main()
{
int option = 1;
char abstract='a';
while(option == 1){
char temp;
cin>> temp;
abstract = temp;
cout << abstract;
option = 1;
if(abstract == '!'){
option = 0;
}
}
return 0;
}
And when I typed something like: abcdefg
all the characters are on the screen,why? It's just because of the compiler?
In fact, only one character at a time is stored in your char. cin>>temp; reads a single char at a time since more characters would not fit there. The loop simply reads and prints one character after the other.
As a visualization hint, try echoing your characters with cout<<abstract<<endl;. You will see a single character per line/iteration.
Your terminal does not restrict the number of characters typed in , that's why you can type as many as you want. Your c++ compiler would read only one of the characters because 'temp' is of type char. you can type an 'if' statement to check the number of characters typed in the terminal
Because of the while loop, which processes each character in turn. Not sure what you expected to happen.
Print it out with delimiters to see that there's never more than a single character printed per iteration:
cout << "'" << abstract << "'";
The terminal window itself is responsible for reading the characters and echoing them back to the screen. Your C++ program asks the terminal for characters and, in this sort of program at least, has no effect on how those characters are displayed.

C++ search a string

I am having a really hard time with this problem...
Write a program that reads two strings (that do not contain blanks)
called searchPattern and longSequence.
The program will display in the screen the positions where
searchPattern appears in longSequence.
For example, when
seachPattern is asd
and longSewuence is asdfasdfasdfasdf
(the positions are 0123456789012345)
the program will display 0, 4, 8, 12.
Another example, when
seachPattern is jj
and longSewuence is kjlkjjlkjjjlkjjjkl
(the positions are 012345678901234567)
the program will display 4, 8, 9, 13, 14.
can anyone help?
Some hints:
Read in the two strings. Look up "std::cin" for how to read and "std::string" for how to store the strings.
Look at the std::string class's find() method to search for the substring in the long string.
Have a go and then post what you have done on here. You will find plenty of people happy to help you, but you have to make some effort yourself. :-)
As a starting point, maybe just write the part that reads in the strings. When that is working well, you can add features.
Good luck.
To start thinking about the solution of problems like this, the best way is to think how you would solve it using a pen and paper in as much detail as possible and then try to translate that to code.
I would use Test Driven Development and start out small and build up.
For example, forget about user I/O, and stick with hard-coded data:
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
int main(void) // For now, can be modified later.
{
const char pattern[] = "asd";
const char sequence[] = "asdfasdfasdfasdf";
std::string::size_type position = 0;
const std::string longSequence(sequence);
position = longSequence.find(pattern, position);
while (position != std::string::npos)
{
cout << "pattern found at position: " << position << endl;
position = longSequence.find(pattern, position);
}
cout << "Paused. Press ENTER to continue." << endl;
cin.ignore(100000, '\n');
return 0;
}
You may want to convert the above into using a state machine rather than using std::string::find(). Again, this is just a foundation to build upon.
It's a recursive backtracking problem. Just like getting the mouse out of the maze. Define your base cases and your paths through the data. In the end all you need is a single function of maybe 15 - 20 lines.

Input terminal problems and map

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