How to print out atoi value [closed] - c

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.

Related

Can't type anything when using getchar() in this program

I am studying "The C Programming Language, 2nd Ed." by Brian Kernighan and Dennis Ritchie. I was on Exercise 1-19 of the book. The question asks to define a function reverse(s) which reverses a character string a. And we have to write a program which reverses it's input one at a time.
//This program is working on online compiler but not here
#include <stdio.h>
void reverse(char s[]);
int main(void) {
int h = 0; // sort of automatic variable just to
// keep storing characters in current line
char s[200];
char c;
for (int i = 0; i < 1000; i++)
s[i] = '\0';
while ((c = getchar()) != EOF) {
if (c != '\n') {
s[h++] = c;
} else {
s[h++] = c;
h = 0;
reverse(s);
for (int i = 0; i < 1000; i++)
s[i] = '\0';
}
}
}
void reverse(char s[]) {
int i = 200;
while(i >= 0)
if(s[i--] != '\0')
putchar(s[i]);
printf("\n");
}
So when I run this code with gcc on my system, I don't get any errors while compiling, but I can't type any input for some reason. However, the program runs correctly when I use an online C compiler.
void reverse(char s[]) {
int i = 200;
while(i >= 0)
if(s[i--] != '\0')
putchar(s[i]);
printf("\n");
}
if you postdecrement your string index, you are first using value at 200 position, which is invalid (it's one position out of the array) so you are doing bad. To do it properly, you need to predecrement it, as in:
void reverse(char s[]) {
int i = 200;
while(i >= 0)
if(s[--i] != '\0')
putchar(s[i]);
printf("\n");
}
but there's still an error... as you pass a null terminated string, you cannot be sure of what there is in the array after the null.... (can be another null?) so you have to search for the null from the beginning of the string (and this is good, because the most of the time you will feed the routine short strings, and now you don't depend on the array size, which you assumed by a constant 200. One good way to do it is with the strlen() function, as in:
void reverse(char s[]) {
int i = strlen(s);
while(i >= 0) /* ??? see below */
if(s[--i] != '\0')
putchar(s[i]);
printf("\n");
}
and then, the test you do is not necessary at all (you already found the leftmost null):
void reverse(char s[]) {
int i = strlen(s);
while(i >= 0) /* still more below VVV */
putchar(s[--i]);
printf("\n");
}
... and there's still a little mistake... you have to stop when i <= 0 and not when i < 0 as you are predecrementing now:
void reverse(char s[]) {
int i = strlen(s);
while(i > 0) /* here!! */
putchar(s[--i]);
printf("\n");
}

C program is skipping code statements while compiling and executing [closed]

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.

My program can't output the lines correctly

I'm relatively new in C and I currently reading Kernighan's book.
One of the problems in the book is to create an algorithm that from a input line output the line if it is more than 10 characters long.
The point is I'm frustrated because I cant find what is wrong with my code. I debugged and recreate it many times but still cant find out what's going on!
The escape character from function getl() is '.' (dot), and sometimes works and other times don't. If you compile it and test you will see:
gcc -Wall -o out 'script.c'
The question header from the book is:
“Exercise 1-17. Write a program to print all input lines that are longer than 10 characters.”
I'm sure that's relatively easy, but I really wanted to know why this algorithm is not working as expected, i think it has something to do with '\n'.
If someone could help me find out what's the problem with the code, I would appreciate it.
Code
#include <stdio.h>
#define MAX 10000
int getl(char line[], int lim) {
char c;
int count;
for (count = 0 ; count < lim-1 && (c = getchar()) != '.' ; count++) {
if (c == '\n') {
line[count] = '\n';
count++;
break;
}
line[count] = c;
}
line[count] = '\0';
return count;
}
int main() {
char line[MAX];
int len = 1;
for (; len > 0 ;) {
getl(line, MAX);
len = getl(line, MAX);
if (len >= 10)
printf("%s", line);
}
return 0;
}
Your code almost works. You just seem to have some repeated lines here and there that confuse things.
Specifically, you are calling getl(line, MAX); twice in a row. The first gets the input, but don't save the count, the second has only an empty stdin buffer to work with so no sensible count is saved from that. Removing the first call that don't save the count fixes your issue.
#include <stdio.h>
#define MAX 10000
int getl(char line[], int lim) {
char c = getchar();
int count;
for (count = 0 ; c != '.' ; count++) {
line[count] = c;
c = getchar();
}
line[count++] = '\n';
return count;
}
int main() {
char line[MAX];
int len = 1;
for (; len > 0 ;) {
len = getl(line, MAX);
if (len >= 10)
printf("%s", line);
}
return 0;
}
First, you're calling your getl function twice instead of once (you only want to read lines one by one). Fixing that should work.
Then I think you shouldn't add the trailing '\n' to your lines, just print it when your line is longer than 10 characters, in your code, the '\n' will be counted as a character.
Here's the modified code:
#include <stdlib.h>
#include <stdio.h>
#define MAX 10000
int getl(char line[])
{
char c;
int count;
for (count = 0; count < MAX - 1 && (c = getchar()) != '.' ; count++)
{
if (c == '\n')
break;
line[count] = c;
}
line[count] = '\0';
return (count);
}
int main()
{
char line[MAX];
int len = 1;
while (len > 0)
{
len = getl(line);
if (len >= 10)
printf("%s, c = %i\n", line, len);
}
return (0);
}
This should work. https://ideone.com/cXXRUH
#include <stdio.h>
#define MAX 10000
int getline_length(char line[]) {
char ch;
int count = 0;
printf("\nWaiting for INPUT...");
// Using clear while loop to get input, removing redundent complexity
// Either `.` or `\n` consider End Of Line
while(count < MAX-1 && ((ch = getchar()) != '.' || (ch = getchar()) != '\n')) {
line[count++]=ch;
}
line[count] = '\0';
return count;
}
int main() {
char line[MAX];
while(1) {
// reset array before each input
memset(line, 0, sizeof(line));
int len = getline_length(line); //No need to pass limit
if (len >= 10) {
printf("%s", line);
} else {
printf("len < 10");
}
}
return 0;
}

K&R first edition, exercise 1.18 (test in the for statement is ungainly) [closed]

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

ANSI C programming [closed]

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.

Resources