How to write this without goto:
ob_start();
$a = 0;
echo "START of LEFT<br />";
begin:
if($a > 0) {
echo "CONTENT LEFT: $a<BR />";
<VERY DIFFICULT ALGORHITM>
goto end;
}
<... ALL THE REST CODE OF LEFT ...>
echo "END of LEFT<br /><br />";
$output1 = ob_get_contents();
ob_end_clean();
ob_start();
echo "START of CENTER<br />";
$a = 5; goto begin;
end:
<... ALL THE REST CODE OF CENTER ...>
echo "END of CENTER<br />";
$output2 = ob_get_contents();
ob_end_clean();
// print it
echo $output1.$output2;
To get this echo:
START of LEFT
CONTENT LEFT: 5
END of LEFT
START of CENTER
END of CENTER
Requirements:
1. I'm not allowed to change the order(CORE( echo $a ), and PLUGIN( $a=5 )):
ob_start();
$a = 0;
<ANY CODE>
echo $a;
$output1 = ob_get_contents();
ob_end_clean();
ob_start();
<ANY CODE>
$a = rand(0,10);
$output2 = ob_get_contents();
ob_end_clean();
2. Output must be generated via ob_get_contents();
But I'm allowed to write ANY CODE in places.
// Solvings
ob_get_contents(); Helps only if want to replace few lines in output HTML CODE, but can't change a value of variable, to change the ALGORHYTM(depends of var value), which generates the random HTML code.
Also,
As I checked my code, I understand, that my code, even with GOTO labels statement , DOES NOT going to change the $output1 content ?. How to do that? Is the only way is to recache the $output1 from his beggining. Or maybe I'm able to do this in other ways?
You are familiar with the concept of methods/functions? If not ( and it seems that chances are.. ) you should really learn something about those first. It's then a piece of cake to split functionality out of a monolithic block of code to small, maintainable pieces of code.
Structured programming - http://php.net/manual/en/language.oop5.php
If i understood well what you want to do I would use recursive functions instead of goto. for example look at this math expression parser i've witten in C some time ago:
#include <cstdio>
const long MAX = 100010;
char S[MAX], *p=S;
long eval();
long termen();
long factor();
int main() {
FILE *fin=fopen("evaluare.in", "r");
FILE *fout=fopen("evaluare.out", "w");
fgets(S, MAX, fin);
fprintf(fout, "%ld\n", eval());
return 0;
}
long eval() {
long r = termen();
while ( *p=='+' || *p=='-' ) {
switch ( *p ) {
case '+':
++p; // go over "+"
r += termen();
break;
case '-':
++p; // go over "-"
r -= termen();
break;
}
}
return r;
}
long termen() {
long r = factor();
while ( *p=='*' || *p=='/' ) {
switch ( *p ) {
case '*' :
++p;
r *= factor();
break;
case '/':
++p;
r /= factor();
break;
}
}
return r;
}
long factor() {
long r=0;
if ( *p == '(' ) { // subexpression
++p; // go over '('
r = eval();
++p; // go over ')'
} else {
while ( *p>='0' && *p<='9' ) { // number
r = r*10 + *p - '0';
++p;
}
}
return r;
}
The main idea is to split the code in functions and where you have let's say:
goto apocalypse
you'll have:
Apocalypse();
That's the long story said short.
Related
I want to explode coma from an array value.
My code is.
$to_ids_string = "";
$to_id = $this->input->post('to');
for ($r = 0; $r < count($this->input->post('to')); $r++) {
if ($to_ids_string != "") {
$to_ids_string = $to_ids_string . "," . $to_id[$r];
} else {
$to_ids_string = $to_id[$r];
}
}
echo $to_ids_string;
$a = explode(',', $to_ids_string);
foreach ($a as $item) {
echo("<li>$item</li>");
exit;
}
when i echo $to_ids_string it will return 2,3 but when i loop in foreach it only return 2 not show 3.
Because of your exit, if you use exit like that, then it is the end of your program and it doesn't echo anymore.
You forget to remove exit; from foreach loop. When you write exit, execution of your code stops. Hence you are not getting desired output.
Happens due to exit.
Please remove exit from your code.
It is necessary to create a program that will on the basis of input N car number plate ( eg . " KR 635 B " ) to count the number of vehicles from individual places . At the end of the program to print the amount of vehicles coming from a particular place , and the number of vehicles whose region is not recognized . Places that recognizes :
KR - Karlovac
BJ Bjelovar ...
I need a piece of code that identifies the first part of plate lets say: " KR " , because when I use if ( input = " KR " );
then recognizes only if I enter " KR " and not the entire registration .
You can use the StartsWith method to check the beginning of a string. Example:
if (plate.StartsWith("KR")) {
...
}
If you are checking for muliple vales, you might want to get that part of the string as a separate string. You can get the first two characters:
string region = plate.Substring(0, 2);
Or the characters up to the first space:
string region = plate.Substring(0, plate.IndexOf(' '));
bool again = true;
//variable
int bje = 0;
int zgr = 0;
int spt = 0;
int vzn = 0;
int npo = 0;
//petlja za y/n
while(again)
{
// program unutar loopa
Console.WriteLine("Unesite registarsku oznaku: ");
string unos = Console.ReadLine();
if (unos == "bj")
//
bje++;
else if (unos == "zg")
//
zgr++;
else if (unos == "sp")
//
spt++;
else if (unos == "vz")
//
vzn++;
else
npo++;
Console.WriteLine("Bjelovar: " + bje);
Console.WriteLine("zagreb: " + zgr);
Console.WriteLine("split: " + spt);
Console.WriteLine("varazdin: " + vzn);
Console.WriteLine("Nepoznato: " + npo);
// za ponovan unos loop
Console.WriteLine();
Console.WriteLine("Ponovni unos? (Da/Ne)");
string YN = Console.ReadLine();
while (YN != "Y" && YN != "N" )
{
Console.WriteLine("Wrong entry. Again? (Y/N)");
YN = Console.ReadLine();
}
if (YN == "n")
{
again = false;
}
}
See i need those "if statments" changed for that word recognition and just done that is under the if statment.
My compiler says that not all control paths return a value and it points to a overloaded>> variable function. I am not exactly sure what is causing the problem and any help would be appreciated. I am trying to overload the stream extraction operator to define if input is valid. if it is not it should set a failbit to indicate improper input.
std::istream &operator >> (std::istream &input, ComplexClass &c)//overloading extraction operator
{
int number;
int multiplier;
char temp;//temp variable used to store input
input >> number;//gets real number
// test if character is a space
if (input.peek() == ' ' /* Write a call to the peek member function to
test if the next character is a space ' ' */) // case a + bi
{
c.real = number;
input >> temp;
multiplier = (temp == '+') ? 1 : -1;
}
// set failbit if character not a space
if (input.peek() != ' ')
{
/* Write a call to the clear member function with
ios::failbit as the argument to set input's fail bit */
input.clear(ios::failbit);
}
else
// set imaginary part if data is valid
if (input.peek() == ' ')
{
input >> c.imaginary;
c.imaginary *= multiplier;
input >> temp;
}
if (input.peek() == '\n' /* Write a call to member function peek to test if the next
character is a newline \n */) // character not a newline
{
input.clear(ios::failbit); // set bad bit
} // end if
else
{
input.clear(ios::failbit); // set bad bit
} // end else
// end if
if (input.peek() == 'i' /* Write a call to member function peek to test if
the next character is 'i' */) // test for i of imaginary number
{
input >> temp;
// test for newline character entered
if (input.peek() == '\n')
{
c.real = 0;
c.imaginary = number;
} // end if
else if (input.peek() == '\n') // set real number if it is valid
{
c.real = number;
c.imaginary = 0;
} // end else if
else
{
input.clear(ios::failbit); // set bad bit
}
return input;
}
}
The return statement is only executed inside the last if:
if (input.peek() == 'i' ) {
...
return input;
}
It should be changed to:
if (input.peek() == 'i' ) {
...
}
return input;
Please correct the below code:only.
file already contains entries : 1st row username; 2nd row password.
checkbox status required to write to the third line and need to read or alter only the checkbox status value in the file.
Currently this code is working if there already is a value for the checkbox status value, then it is overwriting, else UI is hanging.
WriteCheckStatusToFile(BOOL& locVar)
{
FILE *l_pFile = NULL;
CString l_strRememberCheck;
l_strRememberCheck = GetExePath() + _T("password");
CString sVar;
sVar.Format(_T("%d"),locVar);
if(NULL != (l_pFile = fopen(l_strRememberCheck, _T("r+"))) )
{
int count = 0;
char c;
while(count != 2)
{
if((c = fgetc(l_pFile)) == '\n') count++;
}
fseek(l_pFile,ftell(l_pFile),SEEK_SET);
fprintf(l_pFile, sVar);
}
l_strRememberCheck.ReleaseBuffer();
fclose(l_pFile);
}
thanks in advance to all!
sam.
This line
fprintf(l_pFile, sVar);
doesn't look right. I think it should be
fprintf(l_pFile, "%s\n", (LPCTSTR) sVar);
The loop could become infinite if the file has less than two linefeeds:
while(count != 2)
I think it should be:
while( (count < 2) && ( ! feof(l_pFile) ) && ( c != EOF ) )
Probably unrelated to your error, but - at least for this code snippet - CString::ReleaseBuffer() doesn't need to be called since you have not called CString::GetBuffer().
l_strRememberCheck.ReleaseBuffer();
This line may be unnecessary as it appears to fseek() to where the file pointer already is:
fseek(l_pFile,ftell(l_pFile),SEEK_SET);
In the event a two-line file is not terminated with a '\n' you would need to print like this:
if ( count == 2 )
{
fprintf(l_pFile, "%s\n", (LPCTSTR) sVar);
}
else
{
fprintf(l_pFile, "\n%s\n", (LPCTSTR) sVar);
}
I would like to replace every blank spaces in a string by a fixnum (which is the number of blank spaces).
Let me give an example:
s = "hello, how are you ?"
omg(s) # => "hello,3how10are2you1?"
Do you see a way (sexy if possible) to update a string like this?
Thank you Rubists :)
gsub can be fed a block for the "replace with" param, the result of the block is inserted into place where the match was found. The argument to the block is the matched string. So to implement this we capture as much whitespace as we can ( /\s+/ ) and feed that into the block each time a section is found, returning that string's length, which gets put back where the whitespace was originally found.
Code:
s = "hello, how are you ?"
res = s.gsub(/\s+/) { |m| m.length }
puts res
# => hello,3how10are2you1?
it is possible to do this via an array split : Javascript example
var s = "hello, how are you ?";
function omg( str ) {
var strArr = str.split('');
var count = 0;
var finalStr = '';
for( var i = 0; i < strArr.length; i++ ) {
if( strArr[i] == ' ' ) {
count++;
}
else
{
if( count > 0 ) {
finalStr += '' + count;
count = 0;
}
finalStr += strArr[i];
}
}
return finalStr
}
alert( omg( s ) ); //"hello,3how10are2you1?"
Lol, this seems the best it can be for javascript