Print values inside the array with an on click event in C++ - c++

Please note that below code is only the idea, and not the actual code. How do I print the characters inside my teststring[] array one at a time when a button is clicked?
const string teststring[] = {
"a",
"b",
"c",
"d",
};
if ( button ).onclick() == true {
int i = 0;
printf("output: %s\r\n", teststring[i]);
i++;
}
It is similar to the code in http://jsfiddle.net/Dfprp/, but this is in JavaScript and instead of numbers, I want the characters that are stored in my teststring array.

If I understood your question correctly, this is what you are looking for
std::string teststring = "abcd"
private void myMethod()
{
int len = teststring.length();
for(int cnt=0; cnt< len; cnt++)
printf("output: %c\n", teststring[i]);
}

Related

Can't seem to get a char array to leave a function and be usable in main

The problem enlies with printf(stringOut). It prints an empty array. The function halfstring appears to work correctly but the string it builds never makes it to main.
int main(int argc, char *argv[])
{
char stringIn[30] = "There is no cow level.\0";
char stringOut[sizeof(stringIn)];
halfstring(stringIn, stringOut);
printf(stringOut);
return 0;
}
halfstring is supposed to take every odd character in a char array and put it into a new char array without using ANY system-defined string functions (i.e. those found in the string.h library including strlen, strcat, strcpy, etc).
void halfstring(char stringIn [], char stringOut [])
{
int i = 0;
int modi;
while(stringIn[i] != '\0')
{
if(i % 2 != 0)
{
stringOut[i] = stringIn[i];
}
i++;
}
}
Inside the function halfstring you skipped the first and second characters of stringOut which probably are containing null characters when being declared this is the reason why you got nothing.
You can solve that by adding a new separate indice k for stringOut:
void halfstring(char stringIn [], char stringOut [])
{
int i = 0,k=0; // create a separate indice for stringOut
int modi;
while(stringIn[i] != '\0')
{
if(i % 2 != 0)
{
stringOut[k] = stringIn[i];
k++; // increment the indice
}
i++;
}
stringOut[k]='\0';
}
1) You don't need to NUL terminate a string literal:
char stringIn[30] = "There is no cow level.\0";
^^
2) Your second array (stringOut) results in something like:
{'T', garbage, 'e', garbage, 'e', garbage, 'a', garbage, 'e' ... };
You need to count the number of chars stored in the 2nd array:
void halfstring(char stringIn [], char stringOut [])
{
int i = 0;
int n = 0;
while(stringIn[i] != '\0')
{
if(i % 2 != 0)
{
stringOut[n++] = stringIn[i];
}
i++;
}
stringOut[n] = '\0';
}
There are several drawbacks in the program.
For starters there is no need to include the terminating zero in the string literal
char stringIn[30] = "There is no cow level.\0";
^^^^
because string literals already have the terminating zero.
Secondly usually standard string functions return pointer to the first character of the target string. This allows to chain at least two functions in one statement.
The first parameter is usually declares the target string while the second parameter declares the source string.
As the source string is not changed in the function it should be declared with the qualifier const.
And at last within the function there is used incorrect index for the target string and the string is not appended with the terminating zero.
Taking this into account the function can be written as it is shown in the demonstrative program below
#include <stdio.h>
char * halfstring( char s1[], const char s2[] )
{
char *p = s1;
while ( *s2 && *++s2 ) *p++ = *s2++;
*p = *s2;
return s1;
}
int main(void)
{
char s1[30] = "There is no cow level.";
char s2[sizeof( s1 )];
puts( halfstring( s2, s1 ) );
return 0;
}
Its output is
hr sn o ee.

Find string inside 2D char array in C

I am trying to find a string which is inside 2D char array and return it's index. For example:
char idTable[255][32];
char tester[] = { 't','e','s','t','e','r','\0' };
memcpy(idTable[43], tester, 7);
uint8_t id = getID(name[0]);
//name is returned from function "char **name = func();"
//but I have the same results when I try using normal char array...
I've had partial success with the first part of the below code, but it is finding a match if a part of the word is the same (one, oneTwo). If I add "else if" to the first "if" it always goes to the "else if".
The rest of the file prints different results for
printf("idTable string lenght:\t %u\n", strlen(idTable[index]));
and
printf("foundMatch string lenght:\t %u\n", strlen(foundMatch));
, unless I add printf("Index:\t %i\n", index);.
uint8_t getID(char *name) {
printf("\nInserted name:\t %s\n", name);
uint8_t index;
for (uint8_t r = 0; r < 255; r++) {
if (strstr(idTable[r], name) != NULL) {
printf("Found '%s' in position:\t %d\n", name, r);
index = r;
}
}
printf("Index:\t %i\n", index); // THIS LINE
char foundMatch[strlen(idTable[index])];
printf("idTable string lenght:\t %u\n", strlen(idTable[index]));
for (uint8_t c=0; c<strlen(idTable[index]); c++) {
foundMatch[c] = idTable[index][c];
}
printf("foundMatch string lenght:\t %u\n", strlen(foundMatch));
if (strcmp(foundMatch, nodeName) == 0) {
printf("Confirmed\n");
return index;
} else {
printf("Second test failed\n");
return 0;
}
}
Why am I getting this strange results and is there a better way to do this?
I don't know how you are initializing your idTable entries, but if you are using the method that you showed at the start of the question you'll have problems. You can't assume all of the space reserved by idTable is initialed to 0's, so idTable[43] isn't a null terminated string. Therefore idTable[43] need not compare equal to the null terminated string "tester".
Also your getID function doesn't return anything despite its signature. So it won't even compile as-is.
Here's a solution in actual C++, not C.
std::array<std::string, 255> idTable;
idTable.at(43) = "tester";
std::pair<std::size_t, std::size_t> findInIdTable(std::string const& what) {
for (unsigned i = 0; i < idTable.size(); ++i) {
std::size_t pos = idTable.at(i).find(what);
if (pos != std::string::npos) {
return std::make_pair(i, pos);
}
}
// if the code reaches this place, it means "not found". Choose how you want to deal with it
// my personal suggestion would be to return std::optional<std::pair<...> instead.
}
If you want to discard the pos value, it's easy to change as well.
Live On Coliru
In the category: Use C++
Of course, use std::array<char, 32> or std::string if possible. I stuck with your choices for this answer:
Live On Coliru
#include <algorithm>
#include <iostream>
#include <cstring>
char idTable[255][32] = { };
int main() {
using namespace std;
// initialize an entry
copy_n("tester", 7, idTable[43]);
// find match
auto match = [](const char* a) { return strcmp(a, "tester") == 0; };
auto index = find_if(begin(idTable), end(idTable), match) - idTable;
// print result
cout << "match at: " << index;
}
Prints
match at: 43
You need to add a nul to the end of the foundMatch array after copying in the idTable row:
foundMatch[strlen(idTable[index])] = '\0';
right before the 'foundMatch string lenght' (length) message.
strlen is an expensive function that walks the string every time. You should call that once, store it in a local variable, then reference that variable rather than calling strlen repeatedly.

Return String array

I don't know if this question is asked. But I couldn't find any clear answer after searching full day on net. I would like to return a string array from a function. Right now I can make a String array by splitting a string.
I am new to this but familiar with Java, very hard to split a string though. I tried as below. Someone please make a function out of it which can be used thru out.
void setup(){
Serial.begin(9600);
Serial.println("Starting..");
// Define
String txt = "A#10,20,30:B#40,50,60:B#70,80,90:A#100,110,120";
int str_len = txt.length() + 1;
char char_array[str_len];
txt.toCharArray(char_array, str_len);
Serial.println(char_array);
char *p = char_array;
char *str;
int i=0;
String arr[20];
while ((str = strtok_r(p, ":", &p)) != NULL) {// delimiter is the semicolon
String stringOne = String(str);
arr[i++]=stringOne;
}
}
void loop(){}
Also is it possible to make String array "arr" size dynamic?

Checking user input with string array

string code[4] = {"G", "O", "B", "R"};
string colorPegs[6] = {"R", "B", "Y", "G", "O", "B"};
string userGuess;
getline(cin,userGuess);
Those are the important lines of code in my question.
The user will input 4 letters, for example "BBYG"
How can I make a for loop that checks the first char of user input with the first char of code, and sees if it matches?
for example:
string code is GOBR
user inputs BBBR. In user input, only one letter matches the code, which is the third B, how can I check for this with a for loop?
Try with this code assuming you want to find a match if they are at the same position :
for(int i = 0; i < code.length(); ++i)
{
if(code[i] == user[i]) return true; // Match found here.
}
return false;
Try this:
#include <algorithm>
int main()
{
std::string code{"GOBR"};
std::string input;
std::cin >> input;
auto match = [&] (char c)
{
return std::find(code.begin(), code.end(), c) != code.end();
};
if (std::any_of(input.begin(), input.end(), match))
{
// match
}
}

Function to replace text in arrays C++

I am having a problem. I need to make a function called replaceText that replaces a targeted text with new text. The null character is not included and if no targetText is found then there is no text replacement.
The parameters are two arrays targetText[] and replacementText[]. This is for an assignment and I cannot use str. Here is my code so far.
void SimpleString::replaceText(char targetText[], char replacementText[])
{
for ( int i = 0; i < MAX_LIST; i++)
{
if( replacementText[i] > MAX_LIST)
{
throw SimpleStringOverflowException("SimpleStringOverflowException: Resulting SImpleString too large.");
}
}
}
Here you go:
void replace_text(char targetText[], char replacementText[])
{
int i;
if(strlen(replacementText) > 0 )
{
for(i=0;i<strlen(replacementText);i++)
{
targetText[i] = replacementText[i];
}
for(i = strlen(replacementText) ; i < strlen (targetText) ; i++)
targetText[i] = '\0';
}
}
I assume you can use strlen....right? if not let me know...
it is so simple dear, just assign characters one by one.
i.e. targetText[i]=replacementText[i]
now just iterate the i until it ends the replacementtext or targettext.