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

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;
}

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);
}`

scanf hangs when copy and paste many line of inputs at a time

This may be a simple question, but I'm new to C, and yet couldn't find any answer. My program is simple, it takes 21 lines of string input in a for loop, and print them after that. The number could be less or greater.
int t = 21;
char *lines[t];
for (i = 0; i < t; i++) {
lines[i] = malloc(100);
scanf("%s", lines[i]);
}
for (int i = 0; i < t; i++) {
printf("%s\n", lines[i]);
free(lines[i]);
}
...
So when I copy & paste the inputs at a time, my program hangs, no error, no crash. It's fine if there's only 20 lines or below. And if I enter by hand line by line, it works normally regardless of number of inputs.
I'm using XCode 5 in Mac OS X 10.10, but I don't think this is the issue.
Update:
I tried to debug it when the program hangs, it stopped when i == 20 at the line below:
0x7fff9209430a: jae 0x7fff92094314 ; __read_nocancel + 20
The issue may be related to scanf, but it's so confused, why the number 20? May be I'm using it the wrong way, great thanks to any help.
Update:
I have tried to compile the program using the CLI gcc. It works just fine. So, it is the issue of XCode eventually. Somehow it prevents user from pasting multiple inputs.
Use fgets when you want to read a string in C , and see this documentation about that function:
[FGETS Function]
So you should use it like this :
fgets (lines[i],100,stdin);
So it'll get the string from the input of the user and you can have a look on these two posts as well about reading strings in C:
Post1
Post2
I hope that this'll help you with your problem.
Edit :
#include <stdio.h>
void main(){
int t = 21;
int i;
char *lines[t];
for (i = 0; i < t; i++) {
lines[i] = malloc(100);
fgets(lines[i],255,stdin);
}
for (i = 0; i < t; i++) {
printf("String %d : %s\n",i, lines[i]);
free(lines[i]);
}
}
This code gives :
As you can see , I got the 21 strings that I entered (From 0 to 20, that's why it stops when i==20).
I tried with your input ,here's the results :
I wrote the same code and ran. It works.
It might contain more than 99 characters (include line feed) per line...
Or it might contain spaces and tabs.
scanf(3)
When one or more whitespace characters (space, horizontal tab \t, vertical tab \v, form feed \f, carriage return \r, newline or linefeed \n) occur in the format string, input data up to the first non-whitespace character is read, or until no more data remains. If no whitespace characters are found in the input data, the scanning is complete, and the function returns.
To avoid this, try
scanf ("%[^\n]%*c", lines[i]);
The whole code is:
#include <stdio.h>
int main() {
const int T = 5;
char lines[T][100]; // length: 99 (null terminated string)
// if the length per line is fixed, you don't need to use malloc.
printf("input -------\n");
for (int i = 0; i < T; i++) {
scanf ("%[^\n]%*c", lines[i]);
}
printf("result -------\n");
for (int i = 0; i < T; i++) {
printf("%s\n", lines[i]);
}
return 0;
}
If you still continue to face the problem, show us the input data and more details. Best regards.

Regarding Stringstreams and clearing them

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.

KRL using a bee sting inside extended quotes

What are valid bee sting expressions within an extended quote?
rule set_persistents {
select when pageview ".*"
noop();
always {
ent:ecount += 1 from 1;
app:acount += 1 from 1;
}
}
rule test_bee_stings {
select when pageview ".*"
pre {
sum = ent:ecount + app:acount;
content = <<
sum is #{sum}<br/>
sum + 1 is #{sum+1}<br/>
ecount is #{ent:ecount}<br/>
acount is #{app:acount}
>>;
}
notify("Results", content) with sticky = true;
}
When I run this I get nothing (never see the notify box). If I remove the ecount and acount lines I get
sum is 2
sum + 1 is 21
What bee sting expressions are valid within an extended quote? Is it any different for a normal quoted string?
Variables used in beestings in extended quotes should already have an assigned value and not be an expression. This is because beestings in extended quotes are evaluated on the client side and not the server side. I would also, for the previously explained reason, advise against using 'sum+1' in a beesting even though it currently works for endpoints that understand JavaScript.
Here is how I would write what you are trying to do:
ruleset a60x546 {
meta {
name "extended-quotes-beesting"
description <<
extended-quotes-beesting
>>
author "Mike Grace"
logging on
}
rule test_bee_stings {
select when pageview ".*"
pre {
ecount = ent:ecount + 1;
acount = app:acount + 1;
sum = ecount + acount;
sumplus = sum + 1;
content = <<
sum is #{sum}<br/>
sum + 1 is #{sumplus}<br/>
ecount is #{ecount}<br/>
acount is #{acount}
>>;
}
{
notify("Results", content) with sticky = true;
}
always {
ent:ecount += 1 from 1;
app:acount += 1 from 1;
}
}
}
action shot of app run several times on example.com using bookmarklet:
*I would also advise against using a previous rules postlude to modify app and entity variables that you then use in the next rule expecting it to be incremented. While what you did works it's semantically messy and would probably be a bit cleaner the way I have demonstrated.
**should be taken with a grain of salt since this is only one crazy guy's opinion. : )*

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...