Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
On page 69 from ANSI C programming by K&R there is an example of a function that works as a special version of Unix program grep.
The code is:
#include <stdio.h>
#define MAXLINE 1000 //max input length
int getlinee(char line[], int max);
int Strindex(char source[], char searchfor[]);
char pattern[] = "ould";
int main ()
{
char line[MAXLINE];
int found =0;
while (getlinee(line,MAXLINE) > 0)
if (Strindex(line, pattern)>=0){
printf("%s", line);
found ++;
}
return found;
} // end of main function
int getlinee (char s[], int lim)
{
int c,i;
i =0;
while (--lim > 0 && (c=getchar()) != EOF && c!= '\n')
s[i++] =c;
if (c =='\n')
s[i++] =c;
s[i] = '\0' ;
return i;
}
int Strindex (char s[], char t[])
{
int i,j,k;
for (i =0; s[i] != '\0'; i++)
for (i =i, k=0; t[k] != '\0' && s[j] == t[k]; j++, k++);
if (k > 0 && t[k] == '\0')
return i;
}
return -1;
} // end of strindex
when I compile it I get
51:1:error: expected identifier or '(' before 'return'
54:1:error: expected identifier or '(' before '}' token
I checked the code number of times and couldn't spot out the error.
Remove your extra
return -1;
} // end of strindex
Also you #include is empty.You are not using any header file.
You have two problems in your code.
(i). Line number 40:
for (i = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
Compiler may raise an error for i = i as Assignment to itself 'i = i'
(ii). Line number 45:
An extra }. Delete this. Then try to build. I make changes your code and it successfully built.
#include <stdio.h>
#define MAXLINE 1000 //max input length
int getlinee(char line[], int max);
int Strindex(char source[], char searchfor[]);
char pattern[] = "ould";
int main()
{
char line[MAXLINE];
int found = 0;
while (getlinee(line, MAXLINE) > 0)
if (Strindex(line, pattern) >= 0) {
printf("%s", line);
found++;
}
return found;
} // end of main function
int getlinee(char s[], int lim) {
int c, i;
i = 0;
while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
s[i++] = c;
if (c == '\n')
s[i++] = c;
s[i] = '\0';
return i;
}
int Strindex(char s[], char t[]) {
int i, j, k;
for (i = 0; s[i] != '\0'; i++)
for (i = 1, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
;
if (k > 0 && t[k] == '\0')
return i;
return -1;
} // end of strindex
}
return -1;
Remove } brace above line with return operator.
If we judge by indent and code structure, I think there's open parentheses missing in line:
for (i =0; s[i] != '\0'; i++)
in last function. So the actual line should look like:
for (i =0; s[i] != '\0'; i++) {
There are more than one error in last function. Another one is that j is not initialized.
As I can conclude, that function should search for index of substring inside string. First loop passes through string s. Second loop passes through second string and compares two strings. If comparison reaches the end of second string, it returns found index, else function exits with index -1.
Related
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 2 years ago.
Improve this question
The following code is for searching a string or character in another string :-
`
#include<stdio.h>
#include<string.h>
int strindex( char primary[] , char searchfor[]){
int k;
for(int i = 0 ; primary[i] != '\0' ; i++){
for(int j = i , k = 0 ; (searchfor[k] != '\0') && (primary[j] == searchfor[k]) ; j++ , k++){
;
}
if( k > 0 && searchfor[k] == '\0'){
return i;
}
}
return -1;
}
int line( char *str ){
int i = 0;
char c;
for (;(c = getchar()) != '\n' && (c != EOF) ; i++){
str[i] = c;
}
if( c = '\n') str[i] = '\n';
str[++i] = '\0';
return i;
}
int main(){
char str1[100] , str2[100];
int i ;
puts("Enter the main string:-");
line(str1);
puts("Enter string to search for:-");
line(str2);
i = strindex(str1 , str2);
if( i >= 0){
printf("String found at index : %d \n",i);
}else{
puts("stirng not found.");
}
puts("");
return 0;
}
`
The compile result :-
PS E:\Workspace\C> gcc p1.c
PS E:\Workspace\C> ./a.exe
Enter the main string:-
this is a demo text
Enter string to search for:-
demo
PS E:\Workspace\C>
I am using visual studio code ,
As we can see that the "if-else" and "print" statements after the function call are not being executed . I have tried a lot , but could not make it . Please someone help me and tell me where I am going wrong ??
int k;
for (int j = i, k = 0; ...) { blahBlahBlah(); }
doSomethingWith(k);
That k in the for loop is not the k declared before it, it's a new variable that shadows (hides) the original. That's because using int inside the for loop is a new declaration for all variables following it.
Then, when it comes time to doSomethingWith(k), that's using the original k, as the other one has gone out of scope.
And, since that original k will have some arbitrary value, hilarity will ensue :-)
The quickest solution is probably to remove the declaration from the for statement:
int j, k;
for (j = i, k = 0; ...) { blahBlahBlah(); }
doSomethingWith(k);
In your case, that would be along the lines of:
int strindex(char *primary, char *searchfor) {
int j, k;
for (int i = 0; primary[i] != '\0'; i++) {
for (j = i, k = 0; (searchfor[k] != '\0') && (primary[j] == searchfor[k]); j++, k++);
if (k > 0 && searchfor[k] == '\0') return i;
}
return -1;
}
As an aside, this is also a problem (in line()):
if (c = '\n') str[i] = '\n'; // First = should be ==, anyway.
str[++i] = '\0';
It preserves the newline character so that you would be looking for "demo\n" in "this is a demo text\n", which won't be found. Better to just use:
str[i] = '\0';
And, on top of that, c should be an int, not a char. That's because it has to cater for all possible char values and EOF.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I try to print out the atoi value from the function that is shown in The C Programming Language but I found out that the previous format for main cant print out the atoi value.
Previously, I have write htoi in C with this format but this time it don't work. The code is shown below:
#include <stdio.h>
#include <ctype.h>
#define MAXLINE 1000
int get_line(char line[], int maxline);
int atoi(char s[]);
int main(void)
{
int len;
char line[MAXLINE];
while ((len = get_line(line, MAXLINE)) > 0) {
atoi(line);
printf("%s", line);
}
return 0;
}
int get_line(char s[], int lim)
{
int c, i;
for (i = 0; i < lim-1 && (c=getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
int atoi(char s[])
{
int i, n, sign;
for (i = 0; isspace(s[i]); i++)
;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')
i++;
for (n = 0; isdigit(s[i]); i++)
n = 10 * n + (s[i] - '0');
return sign * n;
}
It copy the user's input instead of print out the int value converted by atoi which is not my desired result.
You need to assign the result of atoi() to a variable and print that.
while ((len = get_line(line, MAXLINE)) > 0) {
int num = atoi(line);
printf("%d\n", num);
}
As you wrote in your code, atoi returns an int. At that point you have two solutions :
A . You store the returned value in a variable then you print it.
B . You print it without storing it using :
printf("%d",atoi(string));
Note : if you weren't aware of its existence, there is a already a function atoi() in stdlib.h.
I was trying to implement the K&R strindex program. User will be asked to enter a line, if the line contains the string "boi" in it, program will confirm that the line contained the pattern. The problem is, program confirms some other string/strings.
If i enter "şgb" it will confirm that it contains the string "boi". So far, it only happens with "şgb".
https://onlinegdb.com/SyeeO0mzH
#include <stdio.h>
#define MAXLINE_LENGTH 100
char pattern[] = "boi";
int get_line(char line[], int maxlength);
int str_index(char str[], char substr[]);
int main() {
char line[MAXLINE_LENGTH];
while(get_line(line, MAXLINE_LENGTH) > 0) {
if(str_index(line, pattern) >= 0) {
printf("%s", line);
printf("Pattern found above line\n");
}
}
return 0;
}
int get_line(char line[], int maxlength){
int index = 0, character;
while(--maxlength > 0 && (character = getchar()) != EOF && character != '\n') {
line[index++] = character;
}
if(character == '\n') {
line[index++] = character;
}
line[index] = '\0';
return index;
}
int str_index(char str[], char substr[]) {
int i, j, k;
for(i = 0; str[i] != '\0'; i++) {
for(j = i, k = 0; substr[k] != '\0' && str[j] == substr[k]; j++, k++) ;
if(k > 0) {
return i;
}
}
return -1;
}
boi
boi
Pattern found above line
fbajdobadşgbadf
fbajdobadşgbadf
Pattern found above line
şgb
şgb
Pattern found above line
In str_index, if any character in str is the first character in substr, then, when i is such that str[i] is that character, substr[j] == substr[k] will be true in the first iteration of for(j = i, k = 0;…, and k will be incremented. When that loop ends, k > 0 is true, and return i; will be executed.
You need to modify the code so that it returns i only if all the characters in substr have been matched.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I could not had any conclusion about what the "test in loop statement" means in terms of programming. Is it about the tests in loop brackets or in curly brackets which are iterated by the loop ?
Exercise 1.18 is here:
char line[];
int max;
main()
{
int len;
extern int max;
extern char save[];
max = 0;
while((len = getline(line, MAXLINE)))
if (len > max){
max = len;
copy();
}
if (max > 0) printf("%s",save);
}
getline()
{
int c,i;
extern char line[];
for (i=0; i<= MAXLİNE -1 && ((c = getchar())!= EOF) && c != '\n';)
line[i++]=c;
if (c == '\n')
{
line[i] = c;
++i;
}
s[i] = '\0';
return (i) ;
}
copy()
{
int i;
extern char save[];
extern char line[];
int i = 0;
while( (save[i] = line[i] ) != '\0')
++i;
}
Exercise l-18. The test in the for statement of getline above is rather
ungainly. Rewrite the program to make it clearer, but retain the same
behavior at end of file or buffer overflow. Is this behavior the most reasonable?
As it follows from the comments it seems the for loop should be rewritten to make the code more readable.
I can suggest the following solution substituting the for loop for a while loop.
getline()
{
int c, i;
extern char line[];
i = 0;
while ( i <= MAXLINE -1 && ((c = getchar()) != EOF) && c != '\n' )
{
line[i++] = c;
}
if (c == '\n')
{
line[i++] = c;
}
line[i] = '\0';
return i;
}
After rewriting the function I see a bug. The variable c must be initialized and the first sub-condition in the while loop also must be changed.
So the function can look for example like
getline()
{
int c, i;
extern char line[];
i = 0;
c = EOF;
while ( i < MAXLINE - 1 && ((c = getchar()) != EOF) && c != '\n' )
{
line[i++] = c;
}
if (c == '\n')
{
line[i++] = c;
}
line[i] = '\0';
return i;
}
Here is a demonstrative program
#include <stdio.h>
#include <string.h>
#define MAXLINE 10
char line[MAXLINE];
int getline( void )
{
int c, i;
extern char line[];
i = 0;
c = EOF;
while (i < MAXLINE - 1 && ((c = getchar()) != EOF) && c != '\n')
{
line[i++] = c;
}
if (c == '\n')
{
line[i++] = c;
}
line[i] = '\0';
return i;
}
int main( void )
{
int max = 0;
int len;
char save[MAXLINE];
while ((len = getline()))
if (len > max) {
max = len;
strcpy( save, line );
}
if (max > 0) printf("%s", save);
return 0;
}
Its output (if to run as a console application in Windows) might look like
1
123456789
12345
123
1234567
^Z
123456789
I have been learning from the C Programming Language book (K&R) and was writing one of the exercises that removes trailing blanks from an input. I understand that a segmentation fault is at some level a problem having to do with accessing memory that is not accessible, but I have read through this code several times and can't find the error. I would like it very much if someone could help find this error and tell me how to discover errors like this in the future.
#include <stdio.h>
#define MAXLINE 1000
#define CHAR 0 /*character definition*/
#define TRAIL 1 /*determines whether program is in a trailing blank*/
int getinput(char input[], int max);
int trailrem(char input[], char copyto[]);
int len;
int main() {
char line[MAXLINE]; /*current line*/
char newline[MAXLINE];
int i, c, newreturn; /*integer counter, character holder, current line length, and trailrem return value*/
int len;
while((len = getinput(line, MAXLINE)) > 0) {
newreturn = trailrem(line, newline);
for(i = 0; i <= newreturn; ++i)
printf("\n%c\n", newline[i]);
}
}
int getinput(char input[],int max) {
int i, c, line;
for(i = 0; (c = getchar()) != EOF && c != '\n' && c < (max-1); ++i)
input[i] = c;
if(c == '\n') {
input[i] = c;
++i;
}
input[i] = '\0';
return i;
}
int trailrem(char input[], char copy[]) {
int i, j, minusin, state, r;
for(i = len; input[i] != EOF && i >= 0; --i) {
if(input[i] =='\n')
state = TRAIL;
else if((input[i] == ' ' && state == TRAIL) ||( input[i] == '\t' && state == TRAIL))
++minusin;
else if(state == TRAIL && (input[i] != ' ' || input[i] != '\t'))
state = CHAR;
for(j = (r = len-minusin); state == CHAR; --j){
copy[j-2] = input[i];
}
}
copy[r] = '\0';
copy[r-1] = '\n';
return r;
}
So many problems in your code. But the main problem is, you have a global len
int len;
And a local len in the main function.
You are initializing len in main function like this:
while((len = getinput(line, MAXLINE)) > 0)
So the local len is updated. But the global len is still 0.
You are expecting that, you will get the updated value of len in trailrem method but you don't. In trailrem() you will get len equal to 0!
for(i = len; input[i] != EOF && i >= 0; --i)
So i is 0 too. And hence, copy[r-1] = '\n'; will crash, because r-1 can be negative.
Other problems: (BLUEPIXY and WhozCraig mentioned in the comment).
for(i = 0; (c = getchar()) != EOF && c != '\n' && c < (max-1); ++i)
here, c < (max-1) should be i < (max-1).
++minusin; in trailrem function where minusin is uninitialized.