Exemple #1
0
int testString(){
    char testString[] = "reset";

    int stringlength = strlen(testString);
    int i;
    int loopCtr = 0;

    for( i = 0; i < stringlength; i++){
	char *s;
	s = inputString();

	while( testString[i] != s[i]){
		s = inputString();

		loopCtr++;

		if( loopCtr == 100000 ){
			printf("Failure Could not generate: %c at teststring index %i\n", testString[i]);
			exit(1);
		}

	}
	printf("Success:%c == testString[i] at index %i after %i loops\n", s[i], i, loopCtr);
	}
	return 0;

}
Exemple #2
0
/*	addStudents
	function with loop to add students one at a time
	in:  none
	out: none
*/
void addStudents()
{
	// declarations
	char firstName[32];		// store input first name
	char lastName[32];		// store input last name
	int completedCredits;	// store input completed credits
	struct DATE enrollmentDate;	// store input enrollment date
	struct STUDENT *s;		// pointer to a student record
	
	// print header
	printf("Add Students\n============\n\n"
		"Start entering students. Leave first name blank to stop.\n\n");
	
	// outer loop for entering another student
	do {
		// inner loop for repeating incorrect entry
		do {
			// print # entering
			printf("Student #%d\n", numStudents + 1);
			
			// get input from user
			strcpy(firstName, inputString("First name: ", 32));
			if (strcmp(firstName, "") == 0) return;
			
			strcpy(lastName, inputString("Last name: ", 32));
			if (strcmp(lastName, "") == 0) return;
			
			completedCredits = inputInteger("Completed credits: ");
			enrollmentDate = inputDate("Enrollment date (mm/dd/yyyy): ");
			
			// display input info back to user
			printf("\nFirst name: %s\n"
				"Last name: %s\n"
				"Completed credits: %d\n"
				"Enrollment date: %s\n",
					firstName,
					lastName,
					completedCredits,
					formatDate(enrollmentDate));
			
			// repeat if info incorrect
		} while (!confirm("Info correct (y/n) ?"));
		
		// get pointer to new student
		s = &students[numStudents];
		
		// put info into array at pointer
		strcpy(s->firstName, firstName);
		strcpy(s->lastName, lastName);
		s->completedCredits = completedCredits;
		s->enrollmentDate = enrollmentDate;
		
		// increment # of students
		numStudents ++;
	
	// loop if user wants to input another student
	} while (confirm("Add another student (y/n) ?"));
}
Exemple #3
0
/*	editStudent
	edit an existing student, and display details
	as defaults for input
	in:  pointer to a student to edit
	out: none
*/
void editStudent(struct STUDENT *s)
{
	char firstName[32];		// store input first name
	char lastName[32];		// store input last name
	int completedCredits;	// store input credits
	struct DATE enrollmentDate;	// store input enrollment date
	// store an "empty date" to compare with entered date to indicate no change
	struct DATE noDate = {0};
	
	do {
		// display what # student we're editing
		printf("\nEditing Student #%d\n", numStudents + 1);
		
		// input first name & update only if input not empty
		printf("First name: [%s] ", s->firstName);
		strcpy(firstName, inputString("", 32));
		if (strcmp(firstName, "") == 0) strcpy(firstName, s->firstName);
		
		// input last name & update only if input not empty
		printf("Last name: [%s] ", s->lastName);
		strcpy(lastName, inputString("", 32));
		if (strcmp(lastName, "") == 0) strcpy(lastName, s->lastName);
		
		// input completed credits & update only if input not empty
		printf("Completed credits: [%d] ", s->completedCredits);
		completedCredits = inputInteger("");
		if (completedCredits == 0) completedCredits = s->completedCredits;
		
		// input enrollment date & update only if input not empty
		printf("Enrollment date (mm/dd/yyyy): [%s] ", formatDate(s->enrollmentDate));
		enrollmentDate = inputDate("");
		// since inputDate returns a struct DATE, we must check against an "empty" date
		if (compDates(enrollmentDate, noDate) == 0) enrollmentDate = s->enrollmentDate;
		
		// print details entered
		printf("\nFirst name: %s\n"
			"Last name: %s\n"
			"Completed credits: %d\n"
			"Enrollment date: %s\n",
				firstName,
				lastName,
				completedCredits,
				formatDate(enrollmentDate));
		// confirm with user whether info correct, repeat input if not
	} while (!confirm("\nInfo correct (y/n) ?"));
	
	// store entered data back into the record pointed to by s
	strcpy(s->firstName, firstName);
	strcpy(s->lastName, lastName);
	s->completedCredits = completedCredits;
	s->enrollmentDate = enrollmentDate;
}
int _tmain(int argc, TCHAR **argv) {
  for(;;) {
    const String   pattern    = inputString(_T("Enter pattern:"));
    const bool     ignoreCase = inputString(_T("Ignore case[yn]:")) == _T("y");
    const ShiftAnd A(pattern, ignoreCase);
    const int      maxErrors  = inputInt(_T("Enter maxErrors:"));
    for(;;) {
      const String text = inputString(_T("Enter text:"));
      if((text.length() > 0) && text[0] == _T('!')) break;
      const intptr_t i = A.searchApprox(text,maxErrors);
      _tprintf(_T("result:%zd\n"), i);
    }
  }
  return 0;
}
Exemple #5
0
// -------------------------- ConvertASCIIToWord ---------------------
// reverse of ConvertWordToASCII
void ConvertASCIIToWord(const char*String, WORD &wValue)
{
CString hiByteCS, loByteCS, inputString(String);
int pos;
BYTE hiByte, loByte;
   // search for a space, split into 2 there
   // check for x and interpret as hex
   // else just convert it

   pos = inputString.Find(' ');
   if (pos >=1)
   {
      hiByteCS = inputString.Left(pos);
      loByteCS = inputString.Mid(pos+1);
      ConvertASCIIToByte(hiByteCS, hiByte);
      ConvertASCIIToByte(loByteCS, loByte);
      wValue = loByte + (hiByte<<8);
   }
   else
   {
      if (inputString.GetLength() == 2)
      {
         inputString.Insert(1, ' ');
         ConvertASCIIToWord(inputString, wValue);
      }
      else
      {
         ConvertASCIIToByte(inputString, hiByte);
         wValue = hiByte;
      }
   }
}
Exemple #6
0
void testme()
{
  int tcCount = 0;
  char *s;
  char c;
  int state = 0;
  while (1)
  {
    tcCount++;
    c = inputChar();
    s = inputString();
    printf("Iteration %d: c = %c, s = %s, state = %d\n", tcCount, c, s, state);

    if (c == '[' && state == 0) state = 1;
    if (c == '(' && state == 1) state = 2;
    if (c == '{' && state == 2) state = 3;
    if (c == ' '&& state == 3) state = 4;
    if (c == 'a' && state == 4) state = 5;
    if (c == 'x' && state == 5) state = 6;
    if (c == '}' && state == 6) state = 7;
    if (c == ')' && state == 7) state = 8;
    if (c == ']' && state == 8) state = 9;
    if (s[0] == 'r' && s[1] == 'e'
       && s[2] == 's' && s[3] == 'e'
       && s[4] == 't' && s[5] == '\0'
       && state == 9)
    {
      printf("error ");
      exit(200);
    }
  }
}
Exemple #7
0
void QgsRequestHandler::parseInput()
{
  if ( mRequest.method() == QgsServerRequest::PostMethod )
  {
    QString inputString( mRequest.data() );

    QDomDocument doc;
    QString errorMsg;
    int line = -1;
    int column = -1;
    if ( !doc.setContent( inputString, true, &errorMsg, &line, &column ) )
    {
      // XXX Output error but continue processing request ?
      QgsMessageLog::logMessage( QStringLiteral( "Warning: error parsing post data as XML: at line %1, column %2: %3. Assuming urlencoded query string sent in the post body." )
                                 .arg( line ).arg( column ).arg( errorMsg ) );

      // Process input string as a simple query text

      typedef QPair<QString, QString> pair_t;
      QUrlQuery query( inputString );
      QList<pair_t> items = query.queryItems();
      Q_FOREACH ( const pair_t &pair, items )
      {
        mRequest.setParameter( pair.first.toUpper(), pair.second );
      }
Exemple #8
0
uint8_t edpComposeCommand(uint8_t srcEdpAddr, uint8_t* cmdBuffer)
{
	uint8_t string[80];
	uint8_t len;
	uint8_t i;

	// instructions
	rprintfProgStrM("Enter EDP Command, format [c][p1][p2][p3]...[pN]\r\n");
	rprintfProgStrM("[c] is command char, [px] parameters in 2-digit hex\r\n");

	// get user input
	rprintfProgStrM("EDP Command>");
	len = inputString(0x0D, 80, string);
	rprintfCRLF();

	// check for null user input
	if(!len)
	{
		rprintfProgStrM("ERROR: No command\r\n");
		// return immediately with zero command length
		return 0;
	}

	// prepare command
	cmdBuffer[0] = srcEdpAddr;
	cmdBuffer[1] = string[0];
	for(i=0; i<len/2; i++)
	{
		cmdBuffer[i+2] = asciiHexToByte(&string[1+(i*2)]);
	}

	// return command length
	return 2+(len/2);
}
Exemple #9
0
int HiRes5Engine::o_checkItemTimeLimits(ScriptEnv &e) {
	OP_DEBUG_1("\tCHECK_ITEM_TIME_LIMITS(VARS[%d])", e.arg(1));

	bool lostAnItem = false;
	Common::List<Item>::iterator item;

	for (item = _state.items.begin(); item != _state.items.end(); ++item) {
		const byte room = item->room;
		const byte region = item->region;

		if (room == IDI_ANY || room == IDI_CUR_ROOM || (room == _state.room && region == _state.region)) {
			if (getVar(e.arg(1)) < _itemTimeLimits[item->id - 1]) {
				item->room = IDI_VOID_ROOM;
				lostAnItem = true;
			}
		}
	}

	if (lostAnItem) {
		printString(_gameStrings.itemTimeLimit);
		inputString();
	}

	return 1;
}
void compress(const std::string& str) {
	// First let's make a copy of our string
	std::string inputString(str);
	// Let's check that our string isn't empty
	if (inputString.empty())
		return;
	// We need two characters to traverse through the string
	char current;
	char next;
	// A counter to keep track of the current letter
	int count = 1;
	// And finally a string where we will keep our answer
	std::string finalString;

	for (int i = 0; i < inputString.length(); i++) {
		current = inputString[i];
		next = inputString[i+1];
		if (current == next) {
			count++;
		}
		else {
			finalString += current;
			finalString += std::to_string(count);
			count = 1;
		}
	}
	if (finalString.length() < inputString.length())
		std::cout << finalString << std::endl;
	else
		std::cout << inputString << std::endl;
}
//TODO Could use some templates perhaps...
bool BasicPlugin::inputsExist() const {
  //First, check the inputVectors...
  QStringList iv = inputVectorList();
  QStringList::ConstIterator ivI = iv.begin();
  for (; ivI != iv.end(); ++ivI) {
    if (!inputVector(*ivI))
      return false;
  }

  //Now, check the inputScalars...
  QStringList is = inputScalarList();
  QStringList::ConstIterator isI = is.begin();
  for (; isI != is.end(); ++isI) {
    if (!inputScalar(*isI))
      return false;
  }

  //Finally, check the inputStrings...
  QStringList istr = inputStringList();
  QStringList::ConstIterator istrI = istr.begin();
  for (; istrI != istr.end(); ++istrI) {
    if (!inputString(*istrI))
      return false;
  }
  return true;
}
Exemple #12
0
void HiRes5Engine::runIntro() {
	insertDisk(2);

	StreamPtr stream(_disk->createReadStream(0x10, 0x0, 0x00, 31));

	_display->setMode(DISPLAY_MODE_HIRES);
	_display->loadFrameBuffer(*stream);
	_display->updateHiResScreen();

	inputKey();

	_display->home();
	_display->setMode(DISPLAY_MODE_TEXT);

	stream.reset(_disk->createReadStream(0x03, 0xc, 0x34, 1));
	Common::String menu(readString(*stream));

	while (!g_engine->shouldQuit()) {
		_display->home();
		_display->printString(menu);

		Common::String cmd(inputString());

		// We ignore the backup and format menu options
		if (!cmd.empty() && cmd[0] == APPLECHAR('1'))
			break;
	};
}
void RecipientsHandler::ConvertSemicolonDelimitedListToWStringCollection(const std::wstring& list, std::vector<const std::wstring>& collection)
{
	std::wstring inputString(list);
	inputString = trim(inputString);

	if(inputString.empty())
		return;

	std::wstring::size_type pos = inputString.find(L";", 0);
	if(inputString.npos == pos)
	{
		collection.push_back(inputString);
		return;
	}

	while(inputString.npos != pos)
	{
		collection.push_back(trim(inputString.substr(0, pos)));
		inputString.erase(0, pos + 1);
		pos = inputString.find(_T(";"), 0);
	}

	inputString = trim(inputString);
	if(inputString.empty())
		return;

	collection.push_back(inputString);
}
TEST(CloneInputStream, NonCloneableInput_NoFallback)
{
  nsTArray<char> inputData;
  testing::CreateData(4 * 1024, inputData);
  nsDependentCSubstring inputString(inputData.Elements(), inputData.Length());

  nsCOMPtr<nsIInputStream> base;
  nsresult rv = NS_NewCStringInputStream(getter_AddRefs(base), inputString);
  ASSERT_TRUE(NS_SUCCEEDED(rv));

  // Take advantage of nsBufferedInputStream being non-cloneable right
  // now.  If this changes in the future, then we need a different stream
  // type in this test.
  nsCOMPtr<nsIInputStream> stream;
  rv = NS_NewBufferedInputStream(getter_AddRefs(stream), base, 4096);
  ASSERT_TRUE(NS_SUCCEEDED(rv));

  nsCOMPtr<nsICloneableInputStream> cloneable = do_QueryInterface(stream);
  ASSERT_TRUE(cloneable == nullptr);

  nsCOMPtr<nsIInputStream> clone;
  rv = NS_CloneInputStream(stream, getter_AddRefs(clone));
  ASSERT_TRUE(NS_FAILED(rv));
  ASSERT_TRUE(clone == nullptr);

  testing::ConsumeAndValidateStream(stream, inputString);
}
Exemple #15
0
void Interface::initOutPipe() {
	return;
	char *garbage = inputString(infoOut,10);
	free(garbage);
	garbage = NULL;
	//garbage string
}
Exemple #16
0
bool TffdshowPageBase::translateTV()
{
    if (page && tr->translateMode) {
        HTREEITEM hti = TreeView_GetDropHilight(htv);
        if (!hti) {
            hti = TreeView_GetSelection(htv);
        }
        ThtiPage *pages = hti2htiPage(hti);
        char_t newtrans[1024] = _l("");
        for (TconfPages::const_iterator page = pages->begin(); page != pages->end(); page++) {
            const char_t *oldtrans = tr->translate((*page)->dialogId);
            if (oldtrans) {
                if (newtrans[0] == '\0') {
                    ff_strncpy(newtrans, oldtrans, countof(newtrans));
                    if (!inputString(_l("Translate"), oldtrans, newtrans, 1024)) {
                        break;
                    }
                }
                tr->newTranslation((*page)->dialogId, 0, newtrans);
            }
        }
        translate();
        return true;
    }
    return false;
}
void SqlRegex::testSqlRegex() {
  for(;;) {
    String pattern = inputString(_T("Enter pattern:"));
    SqlRegex reg(pattern);
    reg.dump();
    for(;;) {
      String text = inputString(_T("Enter text (terminate with empty line):"));
      if(text.length() == 0) break;
      if(reg.match(text)) {
        _tprintf(_T("Match!\n"));
      } else {
        _tprintf(_T("No match!\n"));
      }

    }
  }
}
Exemple #18
0
void Interface::readFromPipe() {
	aleGetScreen();
	return;
	lastFrmInfo.clear();
	char *str = inputString(infoOut,ALE_WIDTH*ALE_HEIGHT*2);
	lastFrmInfo.assign(str);
	free(str);
	str = NULL;
	decodeInfo();
}
int main()
{
	int R, V[10], S[30], D[30], l;
	inputArray(V);
	l = inputString(S);
	encrypting(V, S, D, l);
	outputArray(D, l);
	R = decrypting(D, V, l);
	return 0;
}
Exemple #20
0
/*	confirm
	prints a prompt and asks user to enter y/n
	in:  prompt (const char *) - string to prompt user
	out: 1 if Y/y, 0 otherwise
*/
int confirm(const char *prompt)
{
	char *confirmation;

	// get first character of string input
	confirmation = inputString(prompt, 2);
	// if Y or y, return 1; else return 0
	if (strcmp(confirmation, "y") == 0) return 1;
	else return 0;
}
Exemple #21
0
RoOptionalUtf8 RoCli::ReadRaw(std::string message, bool isPassword, const RoHashSet<char> allowedChars, optional<RoButtonSoundPtr> buttonSound)
{
    RoVector<char> inputChars;
    std::cout << message;
    char ch = 0;
    auto masked_chars = [](const char ch) {
        std::cout << "*";
    };
    auto echo_chars = [](const char ch) {
        std::cout << ch;
    };
    std::function<void(const char)> echo_func = echo_chars;
    if (isPassword)
    {
        echo_func = masked_chars;
    }
    do
    {
        ch = GetCharacter();
        if (isalnum(ch) || allowedChars.empty() || allowedChars.count(ch))
        {
            inputChars.push_back(ch);
            echo_func(ch);
        }
        else if (ch == roKEY_ESC)
        {
            std::cout << std::endl;
            return RoOptionalUtf8{};
        }
        else if (ch == roKEY_BACKSPACE && !inputChars.empty())
        {
            size_t clearCharCount = message.length() + inputChars.size();
            std::cout << "\r";
            for (size_t i = 0; i < clearCharCount; ++i)
            {
                std::cout << ' ';
            }
            inputChars.pop_back();
            std::cout << "\r" << message;
            std::for_each(inputChars.begin(), inputChars.end(), echo_func);
        }
    } while (ch != roKEY_RETURN);
    std::cout << std::endl;
    if (inputChars.empty())
    {
        return RoOptionalUtf8{};
    }
    inputChars.push_back(0);
    std::string inputString(inputChars.begin(), inputChars.end());
    if (buttonSound)
    {
        buttonSound.get()->play();
    }
    return RoOptionalUtf8{ inputString };
}
Exemple #22
0
int Interface::resetInPipe() {
	return SUCCESS;
	std::string x = (toString(resetButton) + ",18\n");
	unsigned int numWrite =  fwrite(x.c_str(), sizeof(char), x.length(), infoIn);
	char *garbage = inputString(infoOut,10);	//garbage string
	free(garbage);
	garbage = NULL;
	if(numWrite != x.length())
		return FAIL;
	return SUCCESS;
}
Exemple #23
0
Date getDate(TCHAR *prompt) {
  for(;;) {
    String s = inputString(_T("%s"), prompt);
    try {
      Date dato(s);
      return dato;
    } catch(Exception e) {
      _tprintf(_T("%s\n"), e.what());
    }
  }
}
Exemple #24
0
/*	findStudent
	routine to find a student (by last name)
	in:  none
	out: none
*/
void findStudent()
{
	// declarations
	int i = 0;					// loop counter
	char *findLastName;			// last name to search
	char *lastName;				// holds "current" student last name in loop
	int found[MAX_STUDENTS];	// array to store indices of found students
	int numFound = 0;			// # of students found
	
	// print header
	printf("FIND STUDENT BY LAST NAME\n\n");
	
	// loop until user quits
	do {
		numFound = 0;		// reset # found to 0
		
		// input last name and convert to lowercase
		findLastName = downcase(inputString("Enter partial or entire last name: ", 32));
		printf("\n\nSearching ... ");
		
		// loop through all student records
		for (i = 0; i < numStudents; i++)
		{
			// set lastName to lowercase of "current" student last name
			lastName = downcase(students[i].lastName);
			
			// if the student last name *contains* the text the user entered
			if (strstr(lastName, findLastName) != NULL)
			{
				found[numFound] = i;	// add student to found students array
				numFound ++;	// increment counter
			}
		}
		// if we didn't find any
		if (numFound == 0) printf("No matches found.\n");
		
		else	// we did find at least one
		{
			// print # students found
			printf("Found %d students:\n\n", numFound);
			
			// loop through found students & print each
			for (i = 0; i < numFound; i++)
			{
				printStudent(&students[found[i]]);
				printf("\n");
			}
		}
		
		// ask user for another search
	} while (confirm("Find another (y/n) ? "));
}
Exemple #25
0
int AdlEngine_v2::askForSlot(const Common::String &question) {
	while (1) {
		_display->printString(question);

		Common::String input = inputString();

		if (shouldQuit())
			return -1;

		if (input.size() > 0 && input[0] >= APPLECHAR('A') && input[0] <= APPLECHAR('O'))
			return input[0] - APPLECHAR('A');
	}
}
Exemple #26
0
static wxArrayString Explode(const wxString& in)
{

#define StateNormal   0
#define StateInString 1

    wxString inputString(in);
    inputString.Trim().Trim(false);

    int state(StateNormal);
    wxArrayString tokens;
    wxString      token;

    if(inputString.IsEmpty())
        return tokens;

    for (size_t i=0; i<inputString.Length(); i++) {
        wxChar ch = inputString.GetChar(i);
        switch (ch) {
        case wxT('"'):
            if (state == StateNormal) {
                state = StateInString;

            } else if (state == StateInString) {
                state = StateNormal;
            }
            if(token.IsEmpty() == false)
                tokens.Add(token);
            token.Clear();
            break;
        case wxT(' '):
            if(state == StateNormal) {
                if(token.IsEmpty() == false)
                    tokens.Add(token);
                token.Clear();

            } else {
                token << ch;
            }
            break;
        default:
            token << ch;
            break;
        }
    }

    if(token.IsEmpty() == false)
        tokens.Add(token);

    return tokens;
}
void AnagramSolver::on_solveButton_clicked()
{
    double t_start,t_end;
    t_start=systemTime();

    QRegExp inputString("[a-z][a-z][a-z]*");
    QString result,value,query;
    QStringList list;

    query=ui->inputWindow->toPlainText();
    if(query.isEmpty())
    {
        ui->outputWindow->setText("Input field cannot be left blank.\nPlease enter an anagram to be solved!");
        ui->elapsedTimeWindow->clear();
        return;
    }
    query=query.trimmed();
    query=query.toLower();
    qSort(query.begin(),query.end());
    if(query.length()<2)
    {
        ui->outputWindow->setText("Invalid input.\nInput word must be at least two characters long.\n");
        ui->elapsedTimeWindow->clear();
        return;
    }
    if(!inputString.exactMatch(query))
    {
        ui->outputWindow->setText("Invalid input.\nInput word must contain only alphabets without any whitespace or special characters.\n");
        ui->elapsedTimeWindow->clear();
        return;
    }
    if(hash.contains(query))
    {
        value=hash.value(query);
        list=value.split(" ",QString::SkipEmptyParts);
        for(int i=0;i<list.size(); i++)
        {
            result.append(list.at(i));
            result.append("\n");
        }
    }
    else
    {
        result="No Solution!\nThis program currently supports only English words.";
    }

    ui->outputWindow->setText(result);
    t_end=systemTime();
    ui->elapsedTimeWindow->setText(QString::number(t_end-t_start));
}
Exemple #28
0
int AdlEngine_v2::o2_save(ScriptEnv &e) {
	OP_DEBUG_0("\tSAVE_GAME()");

	int slot = askForSlot(_strings_v2.saveInsert);

	if (slot < 0)
		return -1;

	saveGameState(slot, "");

	_display->printString(_strings_v2.saveReplace);
	inputString();
	return 0;
}
Exemple #29
0
void Interface::finalizePipe() {
	return;
	while(1) {
		std::string x = (toString(18) + ",18\n");
		fwrite(x.c_str(), sizeof(char), x.length(), infoIn);
		char *str = inputString(infoOut,10);
		if(str[0] == 'D') {
			free(str);
			break;
		}
		free(str);
	}
	closePipes();
}
//< 40자제한
int limitInput(char* str, const int length)
{
	while (TRUE)
	{
		size_t num = 0;
		inputString(str);
		num = strlen(str);
		if(num >= length)
		{
			puts("입력오류:글자제한초과");
		}
		else break;
	}

	return SUCCESS;
}