Hi, how do I found out if a name ends with '&' or at worse contains '&'. Below is a function that gets an inputted line (or name). Is it possible to add functionality to this function that does what I want?
Hi, how do I found out if a name ends with '&' or at worse contains '&'. Below is a function that gets an inputted line (or name). Is it possible to add functionality to this function that does what I want?
Can anyone shed any light on this please?
The simplest should be to add an if statement in your for loop that is similar to the one where you check for a newline. In this case you just substitute it for '&', then proceed to do whatever it is you want to do incase of an ampersand, which you did not mention.
Last edited by Subsonics; 02-16-2010 at 05:33 PM.
You did not add an if statement to your for loop, you changed the one you already had outside of the loop.
You need to do something like this, depending on what you want to do:
Code:for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i){ if(c == '&'){ //do something } else s[i] = c; } if (c == '\n') { s[i] = c; ++i; }
If you imagine a list
textfile1
textfile123
textfile&
file&
file2&
I then want to run a program that chooses the longest from the list that contains a '&'
I think I'm not too far away from it, but my head is melted at this stage.
I'm able to do a computation that selects the longest from the list, but I want to narrow it down to selecting the longest one with '&'. I'm able to discard strings that are less than the longest string but fitting in the & is where I'm struggling. Sorry I'm going around in circles here
You could look into implementing strchr(const char *s, int c) into your program. That will return a NULL pointer if it doesn't find an instance of c in your string. If it is not NULL, then it found at least 1 and you know there is an ampersand.
The keyboard is the standard device used to cause computer errors!
You asked if your function could be modified to detect an ampersand. The function returns the length of the string. You could choose to return ONLY if an ampersand is found by setting a flag to true in the if statement, else return 0 like this:
Or you could use strchr() like stumon suggested outside your function when you compare, or inside, there's lots of different ways that this can be achieved.Code:int getline(char s[], int lim) { int c, i; bool ampersandFound = false; for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i){ if(c == '&') ampersandFound = true; s[i] = c; } if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; if(ampersandFound == true) return i; else return 0; }
Last edited by Subsonics; 02-16-2010 at 08:57 PM.