Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I've tried using both binary search, and while loops and for loops in my searches and the same problem is occurring.
When my original program comes to this function call, the linear search function (displayContent) will always assign -1 to position, and after the function call the program breaks and exits.
I have tried to rearrange my program. Like I said, I tried for loops and while loops with both binary and linear search.
I am also using a structure data type of
struct info
{
string name;
double score[5];
double avg;
};
Here is my function call
cout<<"Please enter the name of the person which you would like to search. ";
getline(cin, name);
cin.ignore();
displayContent(contestant, count, name);
Here is my function definition
void displayContent(info contest[], int quantity, string id)
{
int position=-1;
bool found=false;
for(int index=0;index<quantity && !found;index++)
{
if(contest[index].name.compare(id)==0)
{
found=true;
position=index;
}
}
if(position==-1)
{
cout<<"That person was not one of the contestants.";
}
else
{
cout<<"The scores for "<<contest[position].name<<" are \n Contestant Judge1 Judge2 Judge3 Judge4 Judge5 Average"
<<"\n______________________________________________________________________"<<endl;
cout<<right<<setw(15)<<fixed<<setprecision(1) <<contest[position].name<<setw(10)<<contest[position].score[0]<<setw(8)<<contest[position].score[1]<<setw(8)<<contest[position].score[2]<<setw(8)<<contest[position].score[3]
<<setw(8)<<contest[position].score[4]<<setw(8)<<contest[position].avg<<endl;
}
}
Have you verified that getline does what you expect? Perhaps name contains a line ending character. To rule out problems with input you can try to assign a value to name you know exists in contestant before calling displayContent.
I haven't been able to spot any problems in your search algorithm.
Related
I'm mostly curious about the general pattern that's best practice to implement algorithms where we we're marching along indices on opposite ends of an array.
Here's an example problem from leetcode.
Problem Statement
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example Solution
class Solution {
public:
int trap(int A[], int n) {
int left=0; int right=n-1;
int res=0;
int maxleft=0, maxright=0;
while(left<=right){
if(A[left]<=A[right]){
if(A[left]>=maxleft) maxleft=A[left];
else res+=maxleft-A[left];
left++;
}
else{
if(A[right]>=maxright) maxright= A[right];
else res+=maxright-A[right];
right--;
}
}
return res;
}
};
I've really enjoyed Haskell because of how elegant the solutions tend to be but I'm wondering if sometimes it's better to be able to fall back on imperative programming like is an option in OCaml
This question already has answers here:
How to convert a std::string to const char* or char*
(11 answers)
Closed 1 year ago.
because many posts about this problem are misleading or ambiguous, this is how it works, just for the record (tested):
How to convert an Arduino C++ String to an ANSI C string (char* array) using the String method .c_str()
String myString = "WLAN_123456789"; // Arduino String
char cbuffer[128]=""; // ANSI C string (char* array); adjust size appropriately
strcpy( cbuffer, myString.c_str() );
example (tested):
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println();
String myString = "WLAN_123456789";
char cbuffer[128]="";
Serial.println(myString); // debug
strcpy( cbuffer, myString.c_str() );
Serial.println(cbuffer); // debug
}
void loop() {
}
PS:
the example is for variable Strings and for variable char arrays which are not constant, to be able to be assigned to repeatedly and arbitrarily
(also for constant strings optionally, too).
I know your intension is trying to share "best practise" of using String.c_str(), but I couldn't help to say that your "answer" is exactly the one that cause confusion, misleading or ambiguous that you said. If anyone find String.c_str() usage is misleading or ambiguous, it is because one probably does not read the c_str() on Arduino Reference, or fully understand the pointer well.
Converts the contents of a String as a C-style, null-terminated string. Note that this gives direct access to the internal String buffer and should be used with care. In particular, you should never modify the string through the pointer returned. When you modify the String object, or when it is destroyed, any pointer previously returned by c_str() becomes invalid and should not be used any longer.
String.c_str() return a pointer to char array (i.e. a array of char terminated with a '\0'), in another word const char* ptr = String.c_str() represented exactly what String.c_str() is about. Noticed that it is directly access to the buffer in the String object and you are not supposed to change it. So in most case, you use it like Serial.print(ptr). You only need to get a copy of it (as show in your strcpy) if you want to modified the content of your 'copy'.
To put it simply, if the char array (i.e. String.c_str()) is the banana you want to get from a jungle (i.e. the String object) which consists of the forest, the monkey and the whole nine yards, the String.c_str() point you directly to the banana, nothing more, nothing less.
I'm trying to write a program that will ask the user to enter "how many numbers they want to add", then add all the numbers in a function. I want to create the adding function with a dynamically allocated number of parameters such that there are X "int num{someNumber}," where X is the number of numbers the user wants to add. My current code (very rough) is:
int var = 0;
string multiply(int num);
void testing(int num, multiply(var));
int main(){}
void testing(int num, multiply(var)) {
}//end testing
//Function to append int num{num} to string
string multiply(int num) {
string declaration = "null";
for (int num = 0; num <= var; num++) {
declaration.append("int num" + num);
}//end for
return declaration;
}//end multiply
I realize that there is still work to be done, like removing the last comma, for instance, but is it possible to use a string in a function definition to declare X int num parameters?
Another similar question already exists, check out its answer: Variable number of arguments in C++?
While it is definitely possible to define functions with a variable number of arguments, you may also want to consider defining your program iteratively or recursively instead.
Functions with a variable number of arguments can be very useful at times, but can also lead to strange edge-cases like scanf("%d") which wants to scan an integer, but is not given an address to place it into. The function call is allowed, and the scanned integer overwrites a (possibly important) location in memory.
I am in a pickle right now. I'm having trouble taking in an input of example
1994 The Shawshank Redemption
1994 Pulp Fiction
2008 The Dark Knight
1957 12 Angry Men
I first take in the number into an integer, then I need to take in the name of the Movie into a string using a character array, however i have not been able to get this done.
here is the code atm
while(scanf("%d", &myear) != EOF)
{
i = 0;
while(scanf("%[^\n]", &ch))
{
title[i] = ch;
i++;
}
addNode(makeData(title,myear));
}
The title array is arbitrarily large and the function is to add the data as a node to a linked list. right now the output I keep getting for each node is as follows
" hank Redemption"
" ion"
" Knight"
" Men"
Yes, it oddly prints a space in front of the cut-off title. I checked the variables and it adds the space in the data. (I am not printing the year as that is taken in correctly)
How can I fix this?
You are using the wrong type of argument passed to scanf() -- instead of scanning a character, try scanning to the string buffer immediately. %[^\n] scans an entire string up to (but not including) the newline. It does not scan only one character.
(Marginal secondary problem: I don't know from where you people are getting the idea that scanf() returns EOF at end of input, but it doesn't - you'd be better off reading the documentation instead of making incorrect assumptions.)
I hope you see now: scanf() is hard to get right. It's evil. Why not input the whole line at once then parse it using sane functions?
char buf[LINE_MAX];
while (fgets(buf, sizeof buf, stdin) != NULL) {
int year = strtol(buf, NULL, 0);
const char *p = strchr(buf, ' ');
if (p != NULL) {
char name[LINE_MAX];
strcpy(name, p + 1); // safe because strlen(p) <= sizeof(name)
}
}
have a look at the code below once and help me out by clarifying my doubts.
I have commented my doubts on each lines where i have doubts. Moreover, its a part of code from a huge one. so please ignore the variable declarations and all.
The whole code is working perfect and no errors while compiled.
double Graph::Dijkstra( path_t& path )
{
int* paths = new int[_size];
double min = dijkstra(paths); // **is a function call or not? bcz i didn't found any function in the code**
if(min < 0) { delete[] paths; return -1;}
int i = _size - 1;
while(i>=0)
{
path.push(i); // **when will the program come out of this while loop, i'm wondering how does it breaks?**
i=paths[i];
}
path.push(0);
delete[] paths;
return min;
}
Full coding is available here.
double min = dijkstra(paths); // **is a function call or not? bcz i didn't found any function in the code**
It almost certainly is. However, it could be a free function, member function, function invoked by a macro, or something else. Without seeing the rest of the code, we can only guess.
while(i>=0)
{
path.push(i); // **when will the program come out of this while loop, i'm wondering how does it breaks?**
i=paths[i];
}
The program will come out of the loop as a soon as i is less than zero. If I had to guess, I'd say the each node in the path contains a link to the previous node's index with the last node in a path returning -1 or some other negative number.