Regarding Stringstreams and clearing them - stringstream

I'm trying to write a program that counts how many words are in a file.
This code correctly counts the number of words, but why is it that if i remove the iss.clear(); it will only count the number of words in the first line of the file?
stringstream iss;
while(getline(file, line))
{
iss << line;
while(getline(iss,word, ' '))
{
size++;
}
iss.clear();
}

The statement while(getline(iss,word, ' ')) only gets the first line of the stringstream. Try doing this:
int pos = 0;
stringstream iss;
while(getline(file, line))
{
iss << line;
while(getline(iss,word, ' '))
{
size++;
}
pos += line.length();
iss.tellg(pos);
}
The last two lines positions the read pointer at the end of the new line you added, so the next getline will actually read the next line instead of the first one over and over again.

Related

Trying to count the number of 'a' that are entered

Whenever I try to run the following code to count my characters I constantly get zero instead of the number of characters I have inserted.
#include <stdio.h>
void main() {
int c;
int count = 0;
while ( (c = getchar() != EOF) && c == 'a' ) {
count = count +1;
}
printf("Number of chara: %d", count);
}
I have altered the code to instead only count whenever 'a' comes up, but still only get zero when I enter my characters and hit the return key.
The condition of your while loop evaluates to false when the program reads a character that isn't an 'a', which ends the while loop. Since your program reads characters in the while loop, no more characters get read.
Try checking if the character is an 'a' inside the loop body before updating the counter instead of in the loop condition.
The loop will stop because you set the c=='a'. Try to remove that in your code.
Try this one:
int c;
int count = 0;
while (c = getchar() != EOF ) {
count = count +1;
}
printf("Number of chara: %d", count);
}`

How to let fscanf stop reading after a new line

#include <stdio.h>
#define MAX 1000
int line_counter (FILE *file, char buf[]);
int main(int argc, char *argv[]) {
FILE *ptr_file;
char buf[MAX];
ptr_file = fopen("alice-eg.txt", "r");
if (!ptr_file) {
return 1;
}
int count = 0;
while (fscanf(ptr_file, "%s", buf) == 1) {
printf("%s", buf);
if (buf == '\n') {
return count;
}
else {
count += 1;
}
}
printf("The number of words in this line is: %d", count);
return 0;
}
I want to do something along the lines of this but I have no idea how to make it work as the buf is just a pointer to an array of letters (correct me if I'm wrong I just started with C and my understanding of pointers is still quite bad).
fscanf write the line from the file (separated by ENTER) to the buff array and so if it will read an empty line buff[0] = '\n' so that should be your condition.
Secondly:
while (fscanf(ptr_file, "%s", buf) == 1)
Is wrong since fscanf returns the number of read character and so for the line "abcd" form the file it will return 4 and your loop will stop right away instead of reading the entire file and so your condition should be:
while (fscanf(ptr_file, "%s", buf) != EOF)
since fscanf will return EOF when it will reach the end of the file

Trying to get Javascript to delete the end characters on a stored string further than the last character

So I'm reading characters into a string in Javascript. I want the user to be able to delete characters they have stored, much as one would do in word processing.
function Update() {
if (Input.GetKeyDown("return")) c+= "\n";
if (Input.GetKeyDown("tab")) c+= " ";
if (Input.GetKeyDown("backspace")) c = c.Substring(0, c.Length - 1);
if (Input.inputString.Length != 0)
{
c += Input.inputString;
guiText.text = c;
}
}
The issue I'm running into is that after hitting backspace once, it stops going further back- I can only delete one character. For example, were I to type "example", and then hit backspace twice, I would have "exampl", whereas I would want to have "examp".
I'd love some help on figuring out where I'm going wrong here :) Thanks!
Full code in your question would have been better, You are storing one character at a time right? Try
function Update() {
if (Input.GetKeyDown("return")) c+= "\n";
else if (Input.GetKeyDown("tab")) c+= " ";
else if (Input.GetKeyDown("backspace")) c = c.Substring(0, c.Length - 1);
else if (Input.inputString.Length != 0) c += Input.inputString;
guiText.text = c;
}

Match Tesseract-OCR results to .uzn regions

When specifying the regions using a .uzn file, is there a way to then match the text output to the .uzn region where the text came from?
I found a way to do it by getting the bounding boxes for each character, and using that information to see which region every character belongs to.
// Load the .box file output by Tesseract-OCR, and match each bounding box
// to a character from the text. This is not trivial, because whitespaces
// are present in the text from the .txt, but are missing from the .box
// file.
std::vector<RECT> loadBoxFile(const wchar_t *fileName, const std::wstring &text, int imageHeight)
{
// Open file.
std::ifstream st(fileName);
if (!st.is_open())
throw std::runtime_error("Could not open .box file.");
std::string line;
std::string symbolAscii;
std::wstring symbol;
RECT r = { -1, -1, -1, -1 };
std::vector<RECT> ret;
ret.resize(text.size(), r);
size_t textPos = 0;
while (std::getline(st, line)) {
// Parse a line.
std::istringstream iss(line);
if (!(iss >> symbolAscii >> r.left >> r.top >> r.right >> r.bottom))
throw std::runtime_error("Could not parse .box file line.");
symbol = utf8to16(symbolAscii.c_str());
// We don't try to get the bounding box for '~', because sometimes
// there is a '~' in .box file that is not there in .txt file. It's
// a bug in Tesseract-OCR as far as I know. This is a workaround
// for that case.
if (L"~" == symbol)
continue;
// Now match the symbol for that line to a symbol in the .txt file.
textPos = text.find(symbol, textPos);
// If we couldn't match it then fail.
if (text.npos == textPos)
throw std::runtime_error(std::string() + "Could not match symbol \"" + symbolAscii + "\" from .box file to .txt file.");
// Write the bounding box in the array, at index matching the symbol
// in the .txt file.
r.bottom = imageHeight - r.bottom;
r.top = imageHeight - r.top;
for (int ii = 0; ii < symbol.size(); ii++)
ret[textPos + ii] = r;
// Now increment textPos() so we start searching after the last
// symbol of the currently found symbol.
textPos += symbol.size();
}
return ret;
}

How to animate the command line?

I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:
[======> ] 37%
and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?
One way to do this is to repeatedly update the line of text with the current progress. For example:
def status(percent):
sys.stdout.write("%3d%%\r" % percent)
sys.stdout.flush()
Note that I used sys.stdout.write instead of print (this is Python) because print automatically prints "\r\n" (carriage-return new-line) at the end of each line. I just want the carriage-return which returns the cursor to the start of the line. Also, the flush() is necessary because by default, sys.stdout only flushes its output after a newline (or after its buffer gets full).
There are two ways I know of to do this:
Use the backspace escape character ('\b') to erase your line
Use the curses package, if your programming language of choice has bindings for it.
And a Google revealed ANSI Escape Codes, which appear to be a good way. For reference, here is a function in C++ to do this:
void DrawProgressBar(int len, double percent) {
cout << "\x1B[2K"; // Erase the entire current line.
cout << "\x1B[0E"; // Move to the beginning of the current line.
string progress;
for (int i = 0; i < len; ++i) {
if (i < static_cast<int>(len * percent)) {
progress += "=";
} else {
progress += " ";
}
}
cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%";
flush(cout); // Required.
}
The secret is to print only \r instead of \n or \r\n at the and of the line.
\r is called carriage return and it moves the cursor at the start of the line
\n is called line feed and it moves the cursor on the next line
In the console. If you only use \r you overwrite the previously written line.
So first write a line like the following:
[ ]
then add a sign for each tick
\r[= ]
\r[== ]
...
\r[==========]
and so on.
You can use 10 chars, each representing a 10%.
Also, if you want to display a message when finished, don't forget to also add enough white chars so that you overwrite the previously written equal signs like so:
\r[done ]
below is my answer,use the windows APIConsoles(Windows), coding of C.
/*
* file: ProgressBarConsole.cpp
* description: a console progress bar Demo
* author: lijian <hustlijian#gmail.com>
* version: 1.0
* date: 2012-12-06
*/
#include <stdio.h>
#include <windows.h>
HANDLE hOut;
CONSOLE_SCREEN_BUFFER_INFO bInfo;
char charProgress[80] =
{"================================================================"};
char spaceProgress = ' ';
/*
* show a progress in the [row] line
* row start from 0 to the end
*/
int ProgressBar(char *task, int row, int progress)
{
char str[100];
int len, barLen,progressLen;
COORD crStart, crCurr;
GetConsoleScreenBufferInfo(hOut, &bInfo);
crCurr = bInfo.dwCursorPosition; //the old position
len = bInfo.dwMaximumWindowSize.X;
barLen = len - 17;//minus the extra char
progressLen = (int)((progress/100.0)*barLen);
crStart.X = 0;
crStart.Y = row;
sprintf(str,"%-10s[%-.*s>%*c]%3d%%", task,progressLen,charProgress, barLen-progressLen,spaceProgress,50);
#if 0 //use stdand libary
SetConsoleCursorPosition(hOut, crStart);
printf("%s\n", str);
#else
WriteConsoleOutputCharacter(hOut, str, len,crStart,NULL);
#endif
SetConsoleCursorPosition(hOut, crCurr);
return 0;
}
int main(int argc, char* argv[])
{
int i;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hOut, &bInfo);
for (i=0;i<100;i++)
{
ProgressBar("test", 0, i);
Sleep(50);
}
return 0;
}
PowerShell has a Write-Progress cmdlet that creates an in-console progress bar that you can update and modify as your script runs.
Here is the answer for your question... (python)
def disp_status(timelapse, timeout):
if timelapse and timeout:
percent = 100 * (float(timelapse)/float(timeout))
sys.stdout.write("progress : ["+"*"*int(percent)+" "*(100-int(percent-1))+"]"+str(percent)+" %")
sys.stdout.flush()
stdout.write("\r \r")
As a follow up to Greg's answer, here is an extended version of his function that allows you to display multi-line messages; just pass in a list or tuple of the strings you want to display/refresh.
def status(msgs):
assert isinstance(msgs, (list, tuple))
sys.stdout.write(''.join(msg + '\n' for msg in msgs[:-1]) + msgs[-1] + ('\x1b[A' * (len(msgs) - 1)) + '\r')
sys.stdout.flush()
Note: I have only tested this using a linux terminal, so your mileage may vary on Windows-based systems.
If your using a scripting language you could use the "tput cup" command to get this done...
P.S. This is a Linux/Unix thing only as far as I know...